(和JPA操作单数据源区别不大,单数据源操作数据库,想看JPA操作单数据源的,可以进入这个地址(解释更详细一点):https://blog.csdn.net/Zongzhe520/article/details/115764534)
1.在pom.xml中添加(JPA)相关依赖
<!--引入SpringDataJPA依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.编写全局配置文件application.yml
server:
port: 8888
spring:
datasource:
primary:
jdbc-url: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
secondary:
jdbc-url: jdbc:mysql://127.0.0.1:3306/testdb2?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
hibernate:
ddl-auto: validate
database: mysql
show-sql: true
3.编写业务类
项目结构:
Dao层
(1)操作数据源1 testdb
Article.class
@Data
@Builder
@Entity //表示当前类是一个实体类,并表示接受SpringDataJPA的控制管理
@NoArgsConstructor
@AllArgsConstructor
//如果不特定指哪个表,就默认 类名对应的表
//反之,用注解@Table指定对应特定的表
@Table(name = "article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; //id是唯一的主键并且是自增的类型是IDENTITY,所以加如上两个注解
@Column(nullable = false,length=32)
private String author;
@Column(nullable = false,length=32)
private String title;
@Column(length=512)
private String content;
private Date createTime;
}
ArticleRepository.class
public interface ArticleRepository extends JpaRepository<Article,Long> {
//<Article,Long> Article表示要操作的数据库表对应实体PO,Long 是id属性实体主键的类型
//注意这个方法的名称,JPA会根据方法名自动生成SQL语句
Article findByAuthor(String author); //可以所很智能了
}
(2)操作数据源2 testdb2
Message.class
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Message {
@Id
@GeneratedValue
private int id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String content;
}
MessageRepository
public interface MessageRepository extends JpaRepository<Message,Long> {
Message findByName(String name);
}
4.测试方法
JpaDataSourceTest.class
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class JpaDataSourceTest {
@Resource
ArticleRepository articleRepository;
@Resource
MessageRepository messageRepository;
@Test
public void jpaDataSourceTest(){
Article article=articleRepository.findByAuthor("猪八戒");
System.out.println(article);
Message message=messageRepository.findByName("LDS");
System.out.println(message);
Message addMes=Message.builder()
.id(5)
.content("BBBB")
.name("LPZ")
.build();
messageRepository.save(addMes);
System.out.println("插入成功");
System.out.println(messageRepository.findByName("LP"));
}
}
5.运行结果
数据库插入数据成功:
获取数据库数据成功:(红色箭头就为,jpa可以根据自定义的方法名自动生成SQL语句并执行)
6.随手记