The Java Persistence API is a standard technology that lets you “map” objects to relational databases. The spring-boot-starter-data-jpa POM provides a quick way to get started. It provides the following key dependencies:
- Hibernate: One of the most popular JPA implementations.
- Spring Data JPA: Makes it easy to implement JPA-based repositories.
- Spring ORMs: Core ORM support from the Spring Framework.
Quick Start
Add pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
Create entity
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
public Long id;
public String name;
// ... get set method
Create interface and extends PagingAndSortingRepository
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}
Implement interface UserRepository and extends class SimpleJpaRepository
@Repository
@Transactional
public class UserRepositoryImpl extends SimpleJpaRepository<User, Long> implements UserRepository {
@Autowired
public UserRepositoryImpl(EntityManager em) {
super(User.class, em);
}
public UserRepositoryImpl(JpaEntityInformation<User, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
}
public UserRepositoryImpl(Class<User> domainClass, EntityManager em) {
super(domainClass, em);
}
}
Add properties
server.port=8081
#DataSource settings for mysql
datasource.test.mysql.jdbcUrl=jdbc:mysql://127.0.0.1:3406/ytx_trade
datasource.test.mysql.username=root
datasource.test.mysql.password=123456
datasource.test.mysql.driverClassName=com.mysql.jdbc.Driver
# JPA 相关配置
spring.jpa.database = MYSQL
spring.jpa.generateDdl = true
spring.jpa.hibernate.ddlAuto = create-drop
# 数据源连接
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3406/ytx_trade
spring.datasource.username = root
spring.datasource.password = 123456
Spring Boot Multiple Datasource
This is good article
https://stackoverflow.com/questions/27614301/spring-boot-multiple-datasource
Reference documents
https://docs.spring.io/spring-data/jpa/docs/2.0.6.RELEASE/reference/html/