Springboot--Jpa
dao
package com.bjsxt.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.bjsxt.pojo.Roles; /** * RolesRepository * * */ public interface RolesRepository extends JpaRepository<Roles,Integer> { }
package com.bjsxt.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.bjsxt.pojo.Users; /** * 参数一 T :当前需要映射的实体 * 参数二 ID :当前映射的实体中的OID的类型 * */ public interface UsersRepository extends JpaRepository<Users,Integer>{ }
package com.bjsxt.dao; import java.util.List; import org.springframework.data.repository.Repository; import com.bjsxt.pojo.Users; /** * Repository接口的方法名称命名查询 * * */ public interface UsersRepositoryByName extends Repository<Users, Integer> { //方法的名称必须要遵循驼峰式命名规则。findBy(关键字)+属性名称(首字母要大写)+查询条件(首字母大写) List<Users> findByName(String name); List<Users> findByNameAndAge(String name,Integer age); List<Users> findByNameLike(String name); }
package com.bjsxt.dao; import org.springframework.data.repository.CrudRepository; import com.bjsxt.pojo.Users; /** * CrudRepository接口 * * */ public interface UsersRepositoryCrudRepository extends CrudRepository<Users, Integer> { }
package com.bjsxt.dao; import org.springframework.data.repository.PagingAndSortingRepository; import com.bjsxt.pojo.Users; /** * *PagingAndSortingRepository接口 * */ public interface UsersRepositoryPagingAndSorting extends PagingAndSortingRepository<Users,Integer> { }
package com.bjsxt.dao; import java.util.List; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; import com.bjsxt.pojo.Users; /** * Repository @Query * * */ public interface UsersRepositoryQueryAnnotation extends Repository<Users, Integer> { @Query("from Users where name = ?") List<Users> queryByNameUseHQL(String name); @Query(value="select * from t_users where name = ?",nativeQuery=true) List<Users> queryByNameUseSQL(String name); @Query("update Users set name = ? where id = ?") @Modifying //需要执行一个更新操作 void updateUsersNameById(String name,Integer id); }
package com.bjsxt.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.bjsxt.pojo.Users; /** * *JpaSpecificationExecutor * */ public interface UsersRepositorySpecification extends JpaRepository<Users, Integer>, JpaSpecificationExecutor<Users> { }
pojo
package com.bjsxt.pojo; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="t_menus") public class Menus { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="menusid") private Integer menusid; @Column(name="menusname") private String menusname; @Column(name="menusurl") private String menusurl; @Column(name="fatherid") private Integer fatherid; @ManyToMany(mappedBy="menus") private Set<Roles> roles = new HashSet<>(); public Integer getMenusid() { return menusid; } public void setMenusid(Integer menusid) { this.menusid = menusid; } public String getMenusname() { return menusname; } public void setMenusname(String menusname) { this.menusname = menusname; } public String getMenusurl() { return menusurl; } public void setMenusurl(String menusurl) { this.menusurl = menusurl; } public Integer getFatherid() { return fatherid; } public void setFatherid(Integer fatherid) { this.fatherid = fatherid; } public Set<Roles> getRoles() { return roles; } public void setRoles(Set<Roles> roles) { this.roles = roles; } @Override public String toString() { return "Menus [menusid=" + menusid + ", menusname=" + menusname + ", menusurl=" + menusurl + ", fatherid=" + fatherid + "]"; } }
package com.bjsxt.pojo; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="t_roles") public class Roles { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="roleid") private Integer roleid; @Column(name="rolename") private String rolename; @OneToMany(mappedBy="roles") private Set<Users> users = new HashSet<>(); @ManyToMany(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER) //@JoinTable:映射中间表 //joinColumns:当前表中的主键所关联的中间表中的外键字段 @JoinTable(name="t_roles_menus",joinColumns=@JoinColumn(name="role_id"),inverseJoinColumns=@JoinColumn(name="menu_id")) private Set<Menus> menus = new HashSet<>(); public Integer getRoleid() { return roleid; } public void setRoleid(Integer roleid) { this.roleid = roleid; } public String getRolename() { return rolename; } public void setRolename(String rolename) { this.rolename = rolename; } public Set<Users> getUsers() { return users; } public void setUsers(Set<Users> users) { this.users = users; } public Set<Menus> getMenus() { return menus; } public void setMenus(Set<Menus> menus) { this.menus = menus; } }
package com.bjsxt.pojo; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="t_users") public class Users { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private Integer id; @Column(name="name") private String name; @Column(name="age") private Integer age; @Column(name="address") private String address; @ManyToOne(cascade=CascadeType.PERSIST) //@JoinColumn:维护外键 @JoinColumn(name="roles_id") private Roles roles; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Users [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]"; } public Roles getRoles() { return roles; } public void setRoles(Roles roles) { this.roles = roles; } }
启动类
package com.bjsxt; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
resource
spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/orcl spring.datasource.username=root spring.datasource.password=123456 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
junit
package com.bjsxt.test; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.bjsxt.App; import com.bjsxt.dao.RolesRepository; import com.bjsxt.pojo.Menus; import com.bjsxt.pojo.Roles; /** * 多对多的关联关系的测试 * * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=App.class) public class ManyToManyTest { @Autowired private RolesRepository rolesRepository; /** * 添加测试 */ @Test public void testSave(){ //创建角色对象 Roles r = new Roles(); r.setRolename("项目经理"); //创建菜单对象 Menus menus = new Menus(); menus.setMenusname("xxxx管理系统"); menus.setFatherid(0); Menus menus2 = new Menus(); menus2.setFatherid(1); menus2.setMenusname("项目管理"); //关联 r.getMenus().add(menus); r.getMenus().add(menus2); menus.getRoles().add(r); menus2.getRoles().add(r); //保存 this.rolesRepository.save(r); } /** * 查询操作 */ @Test public void testFind(){ Roles roles = this.rolesRepository.findOne(2); System.out.println(roles.getRolename()); Set<Menus> menus = roles.getMenus(); for (Menus menus2 : menus) { System.out.println(menus2); } } }
package com.bjsxt.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.bjsxt.App; import com.bjsxt.dao.UsersRepository; import com.bjsxt.pojo.Roles; import com.bjsxt.pojo.Users; /** * 一对多关联关系测试 * * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=App.class) public class OneToManyTest { @Autowired private UsersRepository usersRepository; /** * 一对多关联关系的添加 */ @Test public void testSave(){ //创建一个用户 Users users = new Users(); users.setAddress("天津"); users.setAge(32); users.setName("小刚"); //创建一个角色 Roles roles = new Roles(); roles.setRolename("管理员"); //关联 roles.getUsers().add(users); users.setRoles(roles); //保存 this.usersRepository.save(users); } /** * 一对多关联关系的查询 */ @Test public void testFind(){ Users findOne = this.usersRepository.findOne(10); System.out.println(findOne); Roles roles = findOne.getRoles(); System.out.println(roles.getRolename()); } }
package com.bjsxt.test; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import org.junit.Test; import org.junit.runner.RunWith; 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.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import org.springframework.data.jpa.domain.Specification; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.bjsxt.App; import com.bjsxt.dao.UsersRepository; import com.bjsxt.dao.UsersRepositoryByName; import com.bjsxt.dao.UsersRepositoryCrudRepository; import com.bjsxt.dao.UsersRepositoryPagingAndSorting; import com.bjsxt.dao.UsersRepositoryQueryAnnotation; import com.bjsxt.dao.UsersRepositorySpecification; import com.bjsxt.pojo.Users; /** * 测试类 * * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = App.class) public class UsersRepositoryTest { @Autowired private UsersRepository usersRepository; @Autowired private UsersRepositoryByName usersRepositoryByName; @Autowired private UsersRepositoryQueryAnnotation usersRepositoryQueryAnnotation; @Autowired private UsersRepositoryCrudRepository usersRepositoryCrudRepository; @Autowired private UsersRepositoryPagingAndSorting usersRepositoryPagingAndSorting; @Autowired private UsersRepositorySpecification usersRepositorySpecification; @Test public void testSave() { Users users = new Users(); users.setAddress("上海市"); users.setAge(24); users.setName("王五"); this.usersRepository.save(users); } /** * Repository--方法名称命名测试 */ @Test public void testFindByName() { List<Users> list = this.usersRepositoryByName.findByName("张三丰"); for (Users users : list) { System.out.println(users); } } /** * Repository--方法名称命名测试 */ @Test public void testFindByNameAndAge() { List<Users> list = this.usersRepositoryByName.findByNameAndAge("王五", 24); for (Users users : list) { System.out.println(users); } } /** * Repository--方法名称命名测试 */ @Test public void testFindByNameLike() { List<Users> list = this.usersRepositoryByName.findByNameLike("王%"); for (Users users : list) { System.out.println(users); } } /** * Repository--@Query测试 注解 */ @Test public void testQueryByNameUseHQL() { List<Users> list = this.usersRepositoryQueryAnnotation.queryByNameUseHQL("王五"); for (Users users : list) { System.out.println(users); } } /** * Repository--@Query测试 */ @Test public void testQueryByNameUseSQL() { List<Users> list = this.usersRepositoryQueryAnnotation.queryByNameUseSQL("王五"); for (Users users : list) { System.out.println(users); } } /** * Repository--@Query测试 */ @Test @Transactional //@Transactional与@Test 一起使用时 事务是自动回滚的。 @Rollback(false) //取消自动回滚 public void testUpdateUsersNameById() { this.usersRepositoryQueryAnnotation.updateUsersNameById("张三三", 1); } /** * CrudRepository测试 */ @Test public void testCrudRepositorySave() { Users user = new Users(); user.setAddress("天津"); user.setAge(32); user.setName("张三丰"); this.usersRepositoryCrudRepository.save(user); } /** * CrudRepository测试 */ @Test public void testCrudRepositoryUpdate() { Users user = new Users(); user.setId(6); user.setAddress("南京"); user.setAge(40); user.setName("张三丰"); this.usersRepositoryCrudRepository.save(user); } /** * CrudRepository测试 */ @Test public void testCrudRepositoryFindOne() { Users users = this.usersRepositoryCrudRepository.findOne(4); System.out.println(users); } /** * CrudRepository测试 */ @Test public void testCrudRepositoryFindAll() { List<Users> list = (List<Users>)this.usersRepositoryCrudRepository.findAll(); for (Users users : list) { System.out.println(users); } } /** * CrudRepository测试 */ @Test public void testCrudRepositoryDeleteById() { this.usersRepositoryCrudRepository.delete(4); } /** * PagingAndSortingRepository 排序测试 */ @Test public void testPagingAndSortingRepositorySort() { //Order 定义排序规则 Order order = new Order(Direction.DESC,"age"); //Sort对象封装了排序规则 Sort sort = new Sort(order); List<Users> list = (List<Users>)this.usersRepositoryPagingAndSorting.findAll(sort); for (Users users : list) { System.out.println(users); } } /** * PagingAndSortingRepository 分页测试 */ @Test public void testPagingAndSortingRepositoryPaging() { //Pageable:封装了分页的参数,当前页,每页显示的条数。注意:他的当前页是从0开始。 //PageRequest(page,size) page:当前页。size:每页显示的条数 Pageable pageable = new PageRequest(1, 5); Page<Users> page = this.usersRepositoryPagingAndSorting.findAll(pageable); System.out.println("总条数:"+page.getTotalElements()); System.out.println("总页数"+page.getTotalPages()); List<Users> list = page.getContent(); for (Users users : list) { System.out.println(users); } } /** * PagingAndSortingRepository 排序+分页 */ @Test public void testPagingAndSortingRepositorySortAndPaging() { Sort sort = new Sort(new Order(Direction.DESC, "id")); Pageable pageable = new PageRequest(1, 2, sort); Page<Users> page = this.usersRepositoryPagingAndSorting.findAll(pageable); System.out.println("总条数:"+page.getTotalElements()); System.out.println("总页数"+page.getTotalPages()); List<Users> list = page.getContent(); for (Users users : list) { System.out.println(users); } } /** * JapRepository 排序测试 */ @Test public void testJpaRepositorySort() { //Order 定义排序规则 Order order = new Order(Direction.DESC,"id"); //Sort对象封装了排序规则 Sort sort = new Sort(order); List<Users> list = this.usersRepository.findAll(sort); for (Users users : list) { System.out.println(users); } } /** * JpaSpecificationExecutor 单条件测试 */ @Test public void testJpaSpecificationExecutor1() { /** * Specification<Users>:用于封装查询条件 */ Specification<Users> spec = new Specification<Users>() { //Predicate:封装了 单个的查询条件 /** * Root<Users> root:查询对象的属性的封装。 * CriteriaQuery<?> query:封装了我们要执行的查询中的各个部分的信息,select from order by * CriteriaBuilder cb:查询条件的构造器。定义不同的查询条件 */ @Override public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // where name = '张三三' /** * 参数一:查询的条件属性 * 参数二:条件的值 */ Predicate pre = cb.equal(root.get("name"), "张三丰"); return pre; } }; List<Users> list = this.usersRepositorySpecification.findAll(spec); for (Users users : list) { System.out.println(users); } } /** * JpaSpecificationExecutor 多条件测试 */ @Test public void testJpaSpecificationExecutor2() { /** * Specification<Users>:用于封装查询条件 */ Specification<Users> spec = new Specification<Users>() { //Predicate:封装了 单个的查询条件 /** * Root<Users> root:查询对象的属性的封装。 * CriteriaQuery<?> query:封装了我们要执行的查询中的各个部分的信息,select from order by * CriteriaBuilder cb:查询条件的构造器。定义不同的查询条件 */ @Override public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // where name = '张三三' and age = 20 List<Predicate> list = new ArrayList<>(); list.add(cb.equal(root.get("name"),"张三丰")); list.add(cb.equal(root.get("age"),20)); Predicate[] arr = new Predicate[list.size()]; return cb.and(list.toArray(arr)); } }; List<Users> list = this.usersRepositorySpecification.findAll(spec); for (Users users : list) { System.out.println(users); } } /** * JpaSpecificationExecutor 多条件测试第二种写法 */ @Test public void testJpaSpecificationExecutor3() { /** * Specification<Users>:用于封装查询条件 */ Specification<Users> spec = new Specification<Users>() { //Predicate:封装了 单个的查询条件 /** * Root<Users> root:查询对象的属性的封装。 * CriteriaQuery<?> query:封装了我们要执行的查询中的各个部分的信息,select from order by * CriteriaBuilder cb:查询条件的构造器。定义不同的查询条件 */ @Override public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // where name = '张三三' and age = 20 /*List<Predicate> list = new ArrayList<>(); list.add(cb.equal(root.get("name"),"张三三")); list.add(cb.equal(root.get("age"),20)); Predicate[] arr = new Predicate[list.size()];*/ //(name = '张三' and age = 20) or id = 2 return cb.or(cb.and(cb.equal(root.get("name"),"张三三"),cb.equal(root.get("age"),20)),cb.equal(root.get("id"), 2)); } }; Sort sort = new Sort(new Order(Direction.DESC,"id")); List<Users> list = this.usersRepositorySpecification.findAll(spec,sort); for (Users users : list) { System.out.println(users); } } }
pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<groupId>com.bjsxt</groupId>
<artifactId>22-spring-boot-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.7</java.version>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 测试工具的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
</dependencies>
</project>