pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
springboot 内置了 jpa 只需要添加一个即可;
application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/myblog?characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
这只是最基础的部分 show_sql啥的没配
由实体类 自动 生成 sql
//表明是实体类
@Entity
public class Blog {
@Id
//自增长
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id ;
@NotEmpty
@Size(min = 2 , max = 50)
@Column(nullable = false , length = 50)
private String title;
@NotEmpty
@Size(min = 2 , max = 300)
@Column(nullable = false)
private String subTitle;
//大字段
@Lob
@Column(name = "content",nullable= false)
//懒加载
@Basic(fetch = FetchType.LAZY)
@NotEmpty
@Size(min=2)
private String content;
@Column(nullable = false)
//自动创建时间戳
@CreationTimestamp
private Timestamp createTime;
@Column(name = "readSize")
private int readSize = 0 ;
@Column(name = "commentSize")
private int commentSize =0 ;
@Column(name = "voteSize")
private int voteSize;
@Column(name = "tags",length = 100)
private String tags;
@ManyToOne(fetch = FetchType.EAGER)
//中间表字段名字
@JoinColumn(name = "user_id")
private User user;
}
值得注意的是
jpa自动生成时间戳什么的类似功能 只有通过jpa插入数据才有效
并不是设置数据库的属性来生成
因此直接操作数据库插入数据是不会自动生成的
jpa DAO层设计
public interface BlogDao extends JpaRepository<Blog, Integer> {
Page<Blog> findByUserEquals(User user,Pageable pageable );
Page<Blog> findByUserAndTitleLike(User user , String title , Pageable pageable );
Page<Blog> findByTitleLikeAndUserOrTagsLikeAndUserOrderByCreateTimeDesc(String title,User user, String tags, Pageable pageable);
}
只要继承JpaRepository 即可 剩下的方法都是自己根据需求来定义 ,
方法的名字都是由规定的 , Jpa 会通过 反射的方式创造sql 来实现dao层的功能 ,根据需求自己定义
具体如下表
关于多对多
我的理解
jointable 即中间表
joinColumns 中间表的字段
joinColumns 维护方(己方)的主键
inverseJoinColumns 被维护方(对方) 主键
@ManyToMany(cascade = CascadeType.DETACH,fetch = FetchType.EAGER)
@JoinTable(name = "user_authority",joinColumns =
@JoinColumn(name = "user_id",referencedColumnName = "id") ,
inverseJoinColumns = @JoinColumn(name = "authority_id", referencedColumnName = "id") )
private List<Authority> authorities;