SpringBoot2.0應用(四):SpringBoot2.0之spring-data-jpa

貳級天災發表於2018-10-31

如何整合spring data jpa

1、pom依賴

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
複製程式碼

2、新增配置

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
複製程式碼

3、建立dto物件

@Entity
public class City implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@SequenceGenerator(name = "city_generator", sequenceName = "city_sequence", initialValue = 23)
	@GeneratedValue(generator = "city_generator")
	private Long id;

	@Column(nullable = false)
	private String name;

	@Column(nullable = false)
	private String state;

	@Column(nullable = false)
	private String country;

	@Column(nullable = false)
	private String map;
    ......
}
複製程式碼

4、建立運算元據的Repository物件

public interface CityRepository extends Repository<City, Long> {

	Page<City> findAll(Pageable pageable);

	Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name,
			String country, Pageable pageable);

	City findByNameAndCountryAllIgnoringCase(String name, String country);

}
複製程式碼

5、寫個簡單的Controller觸發呼叫

@Controller
public class CityController {

    @Autowired
    private CityRepository cityRepository;

    @GetMapping("/")
    @ResponseBody
    @Transactional(readOnly = true)
    public void helloWorld() {
        City city = cityRepository.findByNameAndCountryAllIgnoringCase("Bath", "UK");
        System.out.println(city);

        Page<City> cityPage = cityRepository.findAll(new PageRequest(0,
                10,
                new Sort(Sort.Direction.DESC, "name")));
        System.out.println(Arrays.toString(cityPage.getContent().toArray()));
    }
}
複製程式碼

啟動專案後訪問http://localhost:8080/,控制檯輸出:

Bath,Somerset,UK
[Washington,DC,USA, Tokyo,,Japan, Tel Aviv,,Israel, Sydney,New South Wales,Australia, Southampton,Hampshire,UK, San Francisco,CA,USA, Palm Bay,FL,USA, New York,NY,USA, Neuchatel,,Switzerland, Montreal,Quebec,Canada]
複製程式碼

到此,一個簡單的SpringBoot2.0整合spring-data-jpa就完成了。 spring-data-jpa對一些簡單的資料庫操作進行了支援。具體的關鍵字如下:And,Or,Is,Equals,Between,LessThan,LessThanEqual,GreaterThan,GreaterThanEqual,After,Before,IsNull,IsNotNull,NotNull,Like,NotLike,StartingWith,EndingWith,Containing,OrderBy,Not,In,NotIn,TRUE,FALSE,IgnoreCase。spring-data-jpa對這些關鍵字的支援原理將在原始碼分析篇講解,歡迎關注。

如果有複雜一些的sql語句,依靠上面的關鍵字是肯定不行的,所以spring-data-jpa還提供了註解用來支援自定義sql。在SQL的查詢方法上面使用@Query註解,如涉及到刪除和修改在需要加上@Modifying。 例:

    @Query("select c from City c where c.id = ?1")
    City queryById(long id);

    @Modifying
    @Query("update City c set c.name = ?2 where c.id = ?1")
    int updateNameById(long id, String name);
複製程式碼

注意:自定義sql的語句是對物件進行操作,風格和hql相似。

SQL資料檔案在原始碼中,原始碼地址:GitHub


本篇到此結束,如果讀完覺得有收穫的話,歡迎點贊、關注、加公眾號【貳級天災】,查閱更多精彩歷史!!!

SpringBoot2.0應用(四):SpringBoot2.0之spring-data-jpa

相關文章