SpringBoot整合SpringJPA
引入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
配置配置文件
1.用 application.properties时
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
#连接的什么类型的数据库
spring.jpa.database=MySQL
#控制台打印SQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
# update查看数据库是否有改变字段,有重新建表,没有就不管
# create 每次都会先删除数据库中的表,再创建
spring.jpa.hibernate.ddl-auto=update
2.用 application.yml时
spring:
jpa:
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
database: MySQL
show-sql: true
generate-ddl: true
hibernate:
ddl-auto: update
java代码
serviceImpl
@Override
public User findOne(Integer id) {
Log.get().info("传入的参数 >>>id :{}",id);
Optional<User> byId = userRepository.findById(id);
if (byId.isPresent()){
Log.get().info(">>>>>>>>>>>>>>>>user:{}",byId.get());
}
Log.get().info(">>>>>>>>>>>>>>>>user:{}",byId.get());
return byId.get();
}
dao中
@Repository
public interface UserRepository extends JpaRepository<User,Integer>, JpaSpecificationExecutor<User> {
}
domain中的代码重中之重
@Data
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "type")
private String type;
@Column(name = "monery")
private Integer monery;
}