1、在配置文件中做相关配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/luckymoney?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
2、创建实体类
- 类的属性要和数据库表的属性对应,需要无参构造
- 使用@Entity注解此类
- 使用@Id 和@GeneratedValue 注解主键
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.math.BigDecimal;
@Entity
public class Luckymoney {
@Id
@GeneratedValue
private Integer id;
private BigDecimal money;
private String producer;
private String consumer;
public Luckymoney() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public String getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
public String getConsumer() {
return consumer;
}
public void setConsumer(String consumer) {
this.consumer = consumer;
}
}
3、创建持久层的接口
public interface LuckymoneyRepository extends JpaRepository<Luckymoney,Integer> {
}
4、事务处理
- 使用@Transactional注解,进行事务管理
- 使用的数据库需要支持事务
- 例如MySQL的Innodb支持事务,MyISAM不支持