Spring-data-jpa 依赖于 Hibernate,对Hibernate有必定的了解有助于使用JPA框架。java
<!-- mysql数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <!-- 数据层 Spring-data-jpa --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
#数据库配置 spring.datasource.url=jdbc:mysql://localhost:3306/springboot spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update
# 配置指定对数据库表结构的处理方式,值有:create、create-drop、update、validate # # create:每次加载hibernate的时候,都会从新根据模型生成表。若是表已存在,会先删除该表再生成。 # create-drop:启动项目加载hibernate的时候,会生成表。中止项目时,会把生成的表删除掉。 # update:经常使用属性。每次加载hibernate的时候,会生成表。若是表存在,会根据模型的属性变化来更新表结构,这个过程不会作删表处理。 # validate:每次加载hibernate的时候,会检查表结构,但不会生成表。
package com.sam.demo.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author sam * @since 2017/7/18 */ @Entity @Table(name = "t_person") //指定表名 public class Person { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name; @Column private int age; // getter & setter }
package com.sam.demo.repository; import com.sam.demo.domain.Person; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * @author sam * @since 2017/7/18 */ public interface PersonRepository extends JpaRepository<Person, Long> { Person findByName(String name); Person findByNameAndAge(String name, int age); @Query("FROM Person p WHERE p.id=:id") Person findPersonById(@Param("id") Long id); }
package com.sam.demo.controller; import com.sam.demo.domain.Person; import com.sam.demo.repository.PersonRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author sam * @since 2017/7/16 */ @RequestMapping("/person") @RestController public class PersonController { @Autowired private PersonRepository personRepository; @RequestMapping(method = RequestMethod.GET) public Person index() { Person person = new Person(); person.setName("sam"); person.setAge(25); //保存person personRepository.save(person); // Person temp = personRepository.findPerson(1l); Person temp = personRepository.findByName("sam"); return temp; } }
{"id":1,"name":"sam","age":25}
版权声明:本文为博主原创文章,转载请注明出处。mysql