Spring Boot中使用数据库,这里以MySQL举例。
首先我们知道Spring Boot使用JPA(Java Persistence API)资源库来实现对数据库的操作。那么我们在pom中依赖一下JPA和MySQL:
创建对应的实体
部门:
package com.example.demo.bean;
import javax.persistence.*;
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
public Department(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
用户:
package com.example.demo.bean;
import com.fasterxml.jackson.annotation.JsonBackReference;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = -1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "createdate")
private Date createdate;
@ManyToOne
@JoinColumn(name = "did")
@JsonBackReference//防止关系对象的递归访问
private Department Department;
@ManyToMany(cascade = {}, fetch = FetchType.EAGER)
@JoinTable(name = "user_role",
joinColumns = {@JoinColumn(name = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "roles_id")})
private List<Role> roles;
public User(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
public Department getDeparment() {
return Department;
}
public void setDeparment(Department Department) {
this.Department = Department;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
package com.example.demo.bean;
import javax.persistence.*;
@Entity
@Table(name = "relo")
public class Role{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
public Role(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
接下来,使用JPA对实体持久化,其实只要继承JpaRepository接口就行了:
package com.example.demo.jpaRepository;
import com.example.demo.bean.Department;
import org.springframework.data.jpa.repository.JpaRepository;
public interface DepartmentRepository extends JpaRepository<Department, Long> {}
package com.example.demo.jpaRepository;
import com.example.demo.bean.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, Long> {}
package com.example.demo.jpaRepository;
import com.example.demo.bean.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {}
在MySQL数据中创建一个数据库test,用户名,密码设置为root,root。
然后在Spring Boot的配置文件application.properties中配置数据源和JPA的工作模式
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
最后在test里面写我们的测试程序:(PS:一定要注意写这个注解@SpringBootTest,不然Spring Boot没启动,会报注入错误,哈哈,我就犯傻过,不过人傻就要多读书 )
package com.example.demo;
import com.example.demo.bean.*;
import com.example.demo.jpaRepository.DepartmentRepository;
import com.example.demo.jpaRepository.RoleRepository;
import com.example.demo.jpaRepository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MysqlTest {
private static Logger logger = LoggerFactory.getLogger(MysqlTest.class);
@Autowired
private UserRepository userRepository;
@Autowired
DepartmentRepository DepartmentRepository;
@Autowired
RoleRepository roleRepository;
@Before
public void initData(){
userRepository.deleteAll();
roleRepository.deleteAll();
DepartmentRepository.deleteAll();
Department Department = new Department();
Department.setName("开发部");
DepartmentRepository.save(Department);
Assert.notNull(Department.getId());
Role role = new Role();
role.setName("admin");
roleRepository.save(role);
Assert.notNull(role.getId());
User user = new User();
user.setName("user");
user.setCreatedate(new Date());
user.setDeparment(Department);
List<Role> roles = roleRepository.findAll();
Assert.notNull(roles);
user.setRoles(roles);
userRepository.save(user);
Assert.notNull(user.getId());
}
@Test
public void findPage(){
Pageable pageable = new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "id"));
Page<User> page = userRepository.findAll(pageable);
for (User user : page.getContent()){
logger.info("====user==== user name:{}, Department name:{}, role name: {}", user.getName(),user.getDeparment().getName(), user.getRoles().get(0).getName());
}
}
}
结果如下所示:
再看一下数据库:
已经自动生成表。
最后,Spring Boot使用的是ORM框架hibernate,这个还是很好用的。
好啦,就这么愉快的完成啦。