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