1.映入jpa依賴(lài)
<!--JPA-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2.編寫(xiě)數(shù)據(jù)庫(kù)對(duì)應(yīng)實(shí)體
@Entity
@Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false,unique = true)
private String userName;
@Column(nullable = false)
private String passWord;
@Column(nullable = false,unique = true)
private String email;
@Column(nullable = false,unique = true)
private String nickName;
@Column(nullable = false)
private String regTime;
public User(){
}
public User(String userName, String passWord, String email, String nickName, String regTime) {
this.userName = userName;
this.passWord = passWord;
this.email = email;
this.nickName = nickName;
this.regTime = regTime;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getRegTime() {
return regTime;
}
public void setRegTime(String regTime) {
this.regTime = regTime;
}
}
3.編寫(xiě)UserRepository繼承于JpaRepository条获,JpaRepository中默認(rèn)實(shí)現(xiàn)了多個(gè)方法遮晚,包括增刪改查啄寡。其中Jpa提供多個(gè)數(shù)據(jù)接口颖低,如:
a.CrudRepository 增刪改查接口
b.PagingAndSortingRepository分頁(yè)或 查詢(xún)接口拷窜,繼承與CrudRepository接口俭茧。
c.可以再實(shí)際需求自定義查詢(xún)接口
public interface UserRepository extends JpaRepository<User,Long> {
}
4.在Controller中調(diào)用撬腾,使用 @Autowired引入U(xiǎn)serRepository
@Autowired
private UserRepository userRepository;
@RequestMapping("/home")
@ResponseBody
String getProductData(){
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
String formattedDate = dateFormat.format(date);
userRepository.save(new User("aa1", "aa@126.com", "aa@126.com", "aa123456",formattedDate));
//List<User> mList = userRepository.findAll();
return "success";//+mList.size()
}