SpringBoot+JPA集成项目

以前一直使用的都是mybatis(mybatis-plus)框架操作数据库。前一端时间有个朋友问了一下JPA查询统计后结果集不是一个实体该怎么接收处理的问题?
首先创建maven项目引入下面依赖:pom.xml


    4.0.0
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.5.RELEASE
    
    study-5-domain  
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
         
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
        
        
            org.springframework.boot
            spring-boot-devtools
            true
        

        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.projectlombok
            lombok
            provided
        
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

创建配置文件application.yml。示例:

spring:
  datasource:
    jdbc-url: jdbc:mysql://127.0.0.1:3306/db_comm_01?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: Root1234
    driver-class-name: com.mysql.jdbc.Driver 
  member: 
    datasource:  
      jdbc-url: jdbc:mysql://127.0.0.1:3306/db_member_01?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: Root1234
      driver-class-name: com.mysql.jdbc.Driver 
  jpa: 
    database-platform: org.hibernate.dialect.MySQL5Dialect 
    show-sql: true 
    hibernate: 
      #不自动创建表。
      ddl-auto: none

多数据源配置。
DataSourseConfig.java注入数据源

/**
 * 

数据源配置

* @Author Bertram.Wang * @Date 2019年3月30日 */ @Configuration public class DataSourceConfig { @Bean("dsComm") @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource(){ return DataSourceBuilder.create().build(); } @Bean("dsMember") @ConfigurationProperties(prefix = "spring.member.datasource") public DataSource dataSourceSlave(){ return DataSourceBuilder.create().build(); } }

多个数据源只需要分开设置entityManager, transactionManager即可。分别创建CommDataSourceConfig.java,

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryComm",//配置连接工厂 entityManagerFactory
        transactionManagerRef = "transactionManagerComm", //配置 事物管理器  transactionManager
        basePackages = {"bertram.springcloud.study.repository.comm"}
)
@SuppressWarnings({"rawtypes", "unchecked"})
public class CommDataSourceConfig {
    @Autowired
    @Qualifier("dsComm")
    private DataSource dataSourceMaster;
    @Autowired
    private JpaProperties jpaProperties;

    @Bean("entityManagerComm")
    @Primary
    public EntityManager entityManagerComm(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryComm(builder).getObject().createEntityManager();
    }
    @Bean("entityManagerFactoryComm")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryComm(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dataSourceMaster)
                .properties(getVendorProperties())
                .packages("bertram.springcloud.study.entity.comm")
                .persistenceUnit("commPersistenceUnit")
                .build();

    }
    private Map getVendorProperties() {
        HibernateSettings hibernateSettings = new HibernateSettings();
        return jpaProperties.getHibernateProperties(hibernateSettings);
    }
    @Bean("transactionManagerComm")
    @Primary
    public PlatformTransactionManager transactionManagerComm(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryComm(builder).getObject());
    }
}

MemberDataSourceConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryMember",//配置连接工厂 entityManagerFactory
        transactionManagerRef = "transactionManagerMember", //配置 事物管理器  transactionManager
        basePackages = {"bertram.springcloud.study.repository.member"}
)
@SuppressWarnings({"rawtypes", "unchecked"})
public class MemberDataSourceConfig {

    @Autowired
    @Qualifier("dsMember")
    private DataSource dataSource;
    @Autowired
    private JpaProperties jpaProperties;
    @Bean("entityManagerFactoryMember")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryMember(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dataSource)
                .properties(getVendorProperties())
                .packages("bertram.springcloud.study.entity.member")
                .build();
    }


    @Bean("entityManagerMember")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryMember(builder).getObject().createEntityManager();
    }

    @Bean("transactionManagerMember")
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryMember(builder).getObject());
    }

    private Map getVendorProperties() {
        HibernateSettings hibernateSettings = new HibernateSettings();
        return jpaProperties.getHibernateProperties(hibernateSettings);
    }
}

即可。

对应的repository写在对应的包下面就能分别识别数据源了。

具体文档结构

repository示例:

@Repository
public interface UserRepository extends JpaRepository {
    User findOneById(Integer id);
}
@Repository
public interface MemberRepository extends JpaRepository {
    Member findOneById(Integer id);
}

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode(callSuper=false)
@Entity
@Table(name="sys_user")
public class User implements Serializable {
    private static final long serialVersionUID = -7643897007130979275L;
    @Id
    private Integer id;
    private Date createDate;
    private Date modifyDate;
    private String name;
    private String password;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@EqualsAndHashCode(callSuper=false)
@Entity
@Table(name="member")
public class Member implements Serializable {
    private static final long serialVersionUID = -42305693425865718L;
    @Id
    private Integer id;
    private Date createDate;
    private Date modifyDate;
    private String name;
    private String phone;
    private String password;
}

数据库表:


数据库表

测试:

@RunWith(SpringRunner.class)   
@SpringBootTest(classes={Application.class})// 指定启动类
public class ApplicationTest {
    private static final Logger log = LoggerFactory.getLogger(ApplicationTest.class);
    @Autowired
    UserRepository userRepository;
    @Autowired
    MemberRepository memberRepository;
    @Test
    public void test() {
        User user = userRepository.findOneById(1);
        Member member = memberRepository.findOneById(1);
        log.info("user:{}", user);
        log.info("member:{}", member);
    }
}

执行结果:


执行日志

当我们查询的结果集和实体无对应的时候。
1:直接创建map接收。
示例:

@Query(value="SELECT u.id AS user_id, u.name AS user_name, u.password AS user_password, r.id AS role_id, r.name AS role_name FROM sys_user u LEFT JOIN sys_user_role ur ON ur.user_id = u.id LEFT JOIN sys_role r ON ur.role_id = r.id WHERE u.id = ?1", nativeQuery=true)
Map findOneByUserId(Integer userId);

2:创建一个vo类接收:
示例:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class UserRoleTest {
    @Id
    private Integer userId;
    private String userName;
    private String userPassword;
    private Integer roleId;
    private String roleName;
}


@Repository
public interface UserRoleTestRepository extends JpaRepository {
    @Query(value="SELECT u.id AS user_id, u.name AS user_name, u.password AS user_password, r.id AS role_id, r.name AS role_name FROM sys_user u LEFT JOIN sys_user_role ur ON ur.user_id = u.id LEFT JOIN sys_role r ON ur.role_id = r.id WHERE u.id = ?1", nativeQuery=true)
    UserRoleTest findOneByUserId(Integer userId);
}

测试:

@Test
public void userRoleTest() throws Exception {
    UserRoleTest userRoleTest = userRoleTestRepository.findOneByUserId(1);
    Map map = userRepository.findOneByUserId(1);
    log.info("userRoleTest:{}", userRoleTest);
    log.info("map:{}",new ObjectMapper().writeValueAsString(map));
}

执行结果:


测试结果

注: 后者使用一定要关闭自动生成表功能,否则会生成表格user_role_test.

你可能感兴趣的:(SpringBoot+JPA集成项目)