欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring boot整合jpa

程序员文章站 2022-04-25 07:53:58
...

Githug源码:https://github.com/superRabbitMan/my-spring-boot-jpa

 

本文使用用户、部门、角色的关系来演示整合过程

引入依赖

<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
   </dependency>

   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
   </dependency>

   <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
   </dependency>
   <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
   <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
   </dependency>

</dependencies>

配置yml文件和创建bean

本配置文件只做简单的示例,具体可以参考官方文档

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF8
    username: root
    password: root
  jpa:
    database: MYSQL
    show-sql: true
    hibernate:
      ddl-auto: update
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "com.example.dao")
@EntityScan(basePackages = "com.example.entity")
public class JpaConfiguration {

    @Bean
    PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
        return new PersistenceExceptionTranslationPostProcessor();
    }
    
}

创建实体类

/**
 * 部门表
 * Created by vip on 2018/10/24.
 */
@Entity
@Table(name = "deparment")
public class Deparment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    // get set
}
@Entity
@Table(name = "role")
public class Role implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    //get set
}
@Entity
@Table(name = "user")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "create_date")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createDate;

    @ManyToOne
    @JoinColumn(name = "did")
    @JsonBackReference
    private Deparment deparment;

    @ManyToMany(cascade = {}, fetch = FetchType.EAGER)
    @JoinTable(name = "user_role",
            joinColumns = {@JoinColumn(name = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "roles_id")})
    private List<Role> roles;

    // get set
}

创建数据库表

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for deparment
-- ----------------------------
DROP TABLE IF EXISTS `deparment`;
CREATE TABLE `deparment` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `create_date` datetime DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `did` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FKaakiarxhpooi8qqoe1twj0h5g` (`did`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
  `user_id` bigint(20) NOT NULL,
  `roles_id` bigint(20) NOT NULL,
  KEY `FKeog8p06nu33ihk13roqnrp1y6` (`roles_id`),
  KEY `FK859n2jvi8ivhui0rl0esws6o` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;

创建dao接口

@Repository
public interface DeparmentRepository extends JpaRepository<Deparment, Long> {
}
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

添加访问方法

@RestController
@SpringBootApplication
public class DemoApplication {

   private static Logger logger = LoggerFactory.getLogger(DemoApplication.class);

   @Autowired
   private UserRepository userRepository;
   @Autowired
   private DeparmentRepository deparmentRepository;
   @Autowired
   private RoleRepository roleRepository;

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

   @RequestMapping(value = "/")
   public String home() {
      initDate();
      findPage();
      return "hello spring boot";
   }

   public void initDate() {
      userRepository.deleteAll();
      roleRepository.deleteAll();
      deparmentRepository.deleteAll();

      Deparment deparment = new Deparment();
      deparment.setName("开发部");
      deparmentRepository.save(deparment);
      Assert.notNull(deparment.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(deparment);
      List<Role> roles = roleRepository.findAll();
      Assert.notNull(roles);
      user.setRoles(roles);
      userRepository.save(user);
      Assert.notNull(user.getId());
   }

   public void findPage() {
      Pageable pageable = new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "id"));
      Page<User> page = userRepository.findAll(pageable);
      Assert.notNull(page);
      page.getContent().forEach(user -> {
         logger.info("user name:{}, depa name:{}, role name:{}", user.getName(), user.getDeparment().getName(), user.getRoles().get(0).getName());
      });
   }

}