zero0r1

导航

Spring-data-jpa 在 Spring 中使用

 1 //引入gradle以来
 2 implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
 3 
 4 
 5 //application.properties 写入数据库配置
 6 spring.datasource.url=jdbc:mysql://49.234.00.000:3306/new_schema
 7 spring.datasource.username=zzzz
 8 spring.datasource.password=zzzz
 9 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
10 
11 
12 //查找所有数据
13 @Resource
14 private CoffeeService coffeeService;
15 coffeeService.findAllCoffee()
16 17 //注入Repository
18 @Resource
19 private CoffeeRepository coffeeRepository;
20 
21 public List<Coffee> findAllCoffee() {
22 return coffeeRepository.findAll();
23 }
24 25 //继承JpaRepository
26 import org.springframework.data.jpa.repository.JpaRepository;
27 import redis.demo.model.Coffee;
28 
29 public interface CoffeeRepository extends JpaRepository<Coffee, Long> {
30 }
31 32 //定义Coffee类
33 @EqualsAndHashCode(callSuper = true)
34 @Entity
35 @Table(name = "T_COFFEE")
36 @Builder
37 @Data
38 @ToString(callSuper = true)
39 @NoArgsConstructor
40 @AllArgsConstructor
41 public class Coffee extends BaseEntity implements Serializable {
42 private String name;
43 //gradle 引入 44 //implementation 'org.jadira.usertype:usertype.core:6.0.1.GA' 45 @Type(type = "org.jadira.usertype.moneyandcurrency.joda.PersistentMoneyMinorAmount", 46 parameters = {@org.hibernate.annotations.Parameter(name = "currencyCode", value = "CNY")}) 47 private Money price; 48 } 49 50 //定义BaseEntity 51 @MappedSuperclass 52 @Data 53 @NoArgsConstructor 54 @AllArgsConstructor 55 public class BaseEntity implements Serializable { 56 @Id 57 @GeneratedValue(strategy = GenerationType.IDENTITY) 58 private Long id; 59 @Column(updatable = false) 60 @CreationTimestamp 61 private Date createTime; 62 @UpdateTimestamp 63 private Date updateTime; 64 } 65 66

 

posted on 2019-08-14 00:05  zero0r1  阅读(235)  评论(0编辑  收藏  举报