mirror of
https://github.com/ityouknow/spring-boot-examples.git
synced 2026-06-01 02:19:17 +08:00
add jpa examples
This commit is contained in:
52
spring-boot-jpa/spring-boot-jpa/pom.xml
Normal file
52
spring-boot-jpa/spring-boot-jpa/pom.xml
Normal file
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
|
||||
<groupId>com.neo</groupId>
|
||||
<artifactId>spring-boot-Jpa</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>spring-boot-Jpa</name>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.0.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.neo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
|
||||
@SpringBootApplication
|
||||
public class JpaApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(JpaApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.neo.model;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Address {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long userId;
|
||||
private String province;
|
||||
private String city;
|
||||
private String street;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getProvince() {
|
||||
return province;
|
||||
}
|
||||
|
||||
public void setProvince(String province) {
|
||||
this.province = province;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.neo.model;
|
||||
|
||||
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
@Column(nullable = false, unique = true)
|
||||
private String userName;
|
||||
@Column(nullable = false)
|
||||
private String passWord;
|
||||
@Column(nullable = false, unique = true)
|
||||
private String email;
|
||||
@Column(nullable = true, unique = true)
|
||||
private String nickName;
|
||||
@Column(nullable = false)
|
||||
private String regTime;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String userName, String passWord, String email, String nickName, String regTime) {
|
||||
this.userName = userName;
|
||||
this.passWord = passWord;
|
||||
this.email = email;
|
||||
this.nickName = nickName;
|
||||
this.regTime = regTime;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public String getPassWord() {
|
||||
return passWord;
|
||||
}
|
||||
|
||||
public void setPassWord(String passWord) {
|
||||
this.passWord = passWord;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getNickName() {
|
||||
return nickName;
|
||||
}
|
||||
|
||||
public void setNickName(String nickName) {
|
||||
this.nickName = nickName;
|
||||
}
|
||||
|
||||
public String getRegTime() {
|
||||
return regTime;
|
||||
}
|
||||
|
||||
public void setRegTime(String regTime) {
|
||||
this.regTime = regTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.neo.model;
|
||||
|
||||
|
||||
import org.hibernate.annotations.Fetch;
|
||||
import org.hibernate.annotations.FetchMode;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
public class UserDetail {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
@Column(nullable = false, unique = true)
|
||||
private Long userId;
|
||||
private Integer age;
|
||||
private String realName;
|
||||
private String status;
|
||||
private String hobby;
|
||||
private String introduction;
|
||||
private String lastLoginIp;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getRealName() {
|
||||
return realName;
|
||||
}
|
||||
|
||||
public void setRealName(String realName) {
|
||||
this.realName = realName;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getHobby() {
|
||||
return hobby;
|
||||
}
|
||||
|
||||
public void setHobby(String hobby) {
|
||||
this.hobby = hobby;
|
||||
}
|
||||
|
||||
public String getIntroduction() {
|
||||
return introduction;
|
||||
}
|
||||
|
||||
public void setIntroduction(String introduction) {
|
||||
this.introduction = introduction;
|
||||
}
|
||||
|
||||
public String getLastLoginIp() {
|
||||
return lastLoginIp;
|
||||
}
|
||||
|
||||
public void setLastLoginIp(String lastLoginIp) {
|
||||
this.lastLoginIp = lastLoginIp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "UserDetail{" +
|
||||
"id=" + id +
|
||||
", userId=" + userId +
|
||||
", age=" + age +
|
||||
", realName='" + realName + '\'' +
|
||||
", status='" + status + '\'' +
|
||||
", hobby='" + hobby + '\'' +
|
||||
", introduction='" + introduction + '\'' +
|
||||
", lastLoginIp='" + lastLoginIp + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.neo.model;
|
||||
|
||||
public interface UserInfo {
|
||||
String getUserName();
|
||||
String getEmail();
|
||||
String getHobby();
|
||||
String getIntroduction();
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.neo.param;
|
||||
|
||||
|
||||
import com.neo.model.Address;
|
||||
import org.hibernate.annotations.Fetch;
|
||||
import org.hibernate.annotations.FetchMode;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
public class UserDetailParam {
|
||||
private String userId;
|
||||
private Integer minAge;
|
||||
private Integer maxAge;
|
||||
private String realName;
|
||||
private String introduction;
|
||||
private String city;
|
||||
|
||||
public String getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(String userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Integer getMinAge() {
|
||||
return minAge;
|
||||
}
|
||||
|
||||
public void setMinAge(Integer minAge) {
|
||||
this.minAge = minAge;
|
||||
}
|
||||
|
||||
public Integer getMaxAge() {
|
||||
return maxAge;
|
||||
}
|
||||
|
||||
public void setMaxAge(Integer maxAge) {
|
||||
this.maxAge = maxAge;
|
||||
}
|
||||
|
||||
public String getRealName() {
|
||||
return realName;
|
||||
}
|
||||
|
||||
public void setRealName(String realName) {
|
||||
this.realName = realName;
|
||||
}
|
||||
|
||||
public String getIntroduction() {
|
||||
return introduction;
|
||||
}
|
||||
|
||||
public void setIntroduction(String introduction) {
|
||||
this.introduction = introduction;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.neo.repository;
|
||||
|
||||
import com.neo.model.Address;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface AddressRepository extends JpaRepository<Address, Long> {
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.neo.repository;
|
||||
|
||||
import com.neo.model.User;
|
||||
import com.neo.model.UserDetail;
|
||||
import com.neo.model.UserInfo;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public interface UserDetailRepository extends JpaSpecificationExecutor<UserDetail>,JpaRepository<UserDetail, Long> {
|
||||
|
||||
UserDetail findByHobby(String hobby);
|
||||
|
||||
@Query("select u.userName as userName, u.email as email, d.introduction as introduction , d.hobby as hobby from User u , UserDetail d " +
|
||||
"where u.id=d.userId and d.hobby = ?1 ")
|
||||
List<UserInfo> findUserInfo(String hobby);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.neo.repository;
|
||||
|
||||
import com.neo.model.User;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Slice;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
User findByUserName(String userName);
|
||||
|
||||
User findByUserNameOrEmail(String username, String email);
|
||||
|
||||
@Transactional(timeout = 10)
|
||||
@Modifying
|
||||
@Query("update User set userName = ?1 where id = ?2")
|
||||
int modifyById(String userName, Long id);
|
||||
|
||||
@Transactional
|
||||
@Modifying
|
||||
@Query("delete from User where id = ?1")
|
||||
void deleteById(Long id);
|
||||
|
||||
@Query("select u from User u where u.email = ?1")
|
||||
User findByEmail(String email);
|
||||
|
||||
@Query("select u from User u")
|
||||
Page<User> findALL(Pageable pageable);
|
||||
|
||||
Page<User> findByNickName(String nickName, Pageable pageable);
|
||||
|
||||
Slice<User> findByNickNameAndEmail(String nickName, String email,Pageable pageable);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.neo.service;
|
||||
|
||||
import com.neo.model.UserDetail;
|
||||
import com.neo.param.UserDetailParam;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
public interface UserDetailService {
|
||||
public Page<UserDetail> findByCondition(UserDetailParam detailParam, Pageable pageable);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.neo.service;
|
||||
|
||||
import com.mysql.cj.util.StringUtils;
|
||||
import com.neo.model.UserDetail;
|
||||
import com.neo.param.UserDetailParam;
|
||||
import com.neo.repository.UserDetailRepository;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class UserDetailServiceImpl implements UserDetailService{
|
||||
|
||||
@Resource
|
||||
private UserDetailRepository userDetailRepository;
|
||||
|
||||
@Override
|
||||
public Page<UserDetail> findByCondition(UserDetailParam detailParam, Pageable pageable){
|
||||
|
||||
return userDetailRepository.findAll((root, query, cb) -> {
|
||||
List<Predicate> predicates = new ArrayList<Predicate>();
|
||||
//equal 示例
|
||||
if (!StringUtils.isNullOrEmpty(detailParam.getIntroduction())){
|
||||
predicates.add(cb.equal(root.get("introduction"),detailParam.getIntroduction()));
|
||||
}
|
||||
//like 示例
|
||||
if (!StringUtils.isNullOrEmpty(detailParam.getRealName())){
|
||||
predicates.add(cb.like(root.get("realName"),"%"+detailParam.getRealName()+"%"));
|
||||
}
|
||||
//between 示例
|
||||
if (detailParam.getMinAge()!=null && detailParam.getMaxAge()!=null) {
|
||||
Predicate agePredicate = cb.between(root.get("age"), detailParam.getMinAge(), detailParam.getMaxAge());
|
||||
predicates.add(agePredicate);
|
||||
}
|
||||
//greaterThan 大于等于示例
|
||||
if (detailParam.getMinAge()!=null){
|
||||
predicates.add(cb.greaterThan(root.get("age"),detailParam.getMinAge()));
|
||||
}
|
||||
return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
|
||||
}, pageable);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
|
||||
spring.datasource.username=root
|
||||
spring.datasource.password=root
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
|
||||
spring.jpa.properties.hibernate.hbm2ddl.auto=create
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
|
||||
#sql\u8F93\u51FA
|
||||
spring.jpa.show-sql=true
|
||||
#format\u4E00\u4E0Bsql\u8FDB\u884C\u8F93\u51FA
|
||||
spring.jpa.properties.hibernate.format_sql=true
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.neo;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class JpaApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.neo.repository;
|
||||
|
||||
import com.neo.model.UserDetail;
|
||||
import com.neo.param.UserDetailParam;
|
||||
import com.neo.service.UserDetailService;
|
||||
import com.neo.service.UserDetailServiceImpl;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
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.test.context.junit4.SpringRunner;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class JpaSpecificationTests {
|
||||
|
||||
@Resource
|
||||
private UserDetailService userDetailService;
|
||||
|
||||
@Test
|
||||
public void testFindByCondition() {
|
||||
int page=0,size=10;
|
||||
Sort sort = new Sort(Sort.Direction.DESC, "id");
|
||||
Pageable pageable = PageRequest.of(page, size, sort);
|
||||
UserDetailParam param=new UserDetailParam();
|
||||
param.setIntroduction("程序员");
|
||||
param.setMinAge(10);
|
||||
param.setMaxAge(30);
|
||||
Page<UserDetail> page1=userDetailService.findByCondition(param,pageable);
|
||||
for (UserDetail userDetail:page1){
|
||||
System.out.println("userDetail: "+userDetail.toString());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.neo.repository;
|
||||
|
||||
import com.neo.model.Address;
|
||||
import com.neo.model.User;
|
||||
import com.neo.model.UserDetail;
|
||||
import com.neo.model.UserInfo;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.text.DateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class UserDetailRepositoryTests {
|
||||
|
||||
@Resource
|
||||
private AddressRepository addressRepository;
|
||||
@Resource
|
||||
private UserDetailRepository userDetailRepository;
|
||||
|
||||
@Test
|
||||
public void testSaveAddress() {
|
||||
Address address=new Address();
|
||||
address.setUserId(1L);
|
||||
address.setCity("北京");
|
||||
address.setProvince("北京");
|
||||
address.setStreet("分钟寺");
|
||||
addressRepository.save(address);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSaveUserDetail() {
|
||||
Date date = new Date();
|
||||
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
|
||||
String formattedDate = dateFormat.format(date);
|
||||
UserDetail userDetail=new UserDetail();
|
||||
userDetail.setUserId(3L);
|
||||
userDetail.setHobby("吃鸡游戏");
|
||||
userDetail.setAge(28);
|
||||
userDetail.setIntroduction("一个爱玩的人");
|
||||
userDetailRepository.save(userDetail);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUserInfo() {
|
||||
List<UserInfo> userInfos=userDetailRepository.findUserInfo("钓鱼");
|
||||
for (UserInfo userInfo:userInfos){
|
||||
System.out.println("userInfo: "+userInfo.getUserName()+"-"+userInfo.getEmail()+"-"+userInfo.getHobby()+"-"+userInfo.getIntroduction());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.neo.repository;
|
||||
|
||||
import com.neo.model.User;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.text.DateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class UserRepositoryTests {
|
||||
|
||||
@Resource
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Test
|
||||
public void testSave() {
|
||||
Date date = new Date();
|
||||
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
|
||||
String formattedDate = dateFormat.format(date);
|
||||
|
||||
userRepository.save(new User("aa", "aa123456","aa@126.com", "aa", formattedDate));
|
||||
userRepository.save(new User("bb", "bb123456","bb@126.com", "bb", formattedDate));
|
||||
userRepository.save(new User("cc", "cc123456","cc@126.com", "cc", formattedDate));
|
||||
|
||||
// Assert.assertEquals(3, userRepository.findAll().size());
|
||||
// Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("bb", "bb@126.com").getNickName());
|
||||
// userRepository.delete(userRepository.findByUserName("aa"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testBaseQuery() {
|
||||
Date date = new Date();
|
||||
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
|
||||
String formattedDate = dateFormat.format(date);
|
||||
User user=new User("ff", "ff123456","ff@126.com", "ff", formattedDate);
|
||||
userRepository.findAll();
|
||||
userRepository.findById(3L);
|
||||
userRepository.save(user);
|
||||
user.setId(2L);
|
||||
userRepository.delete(user);
|
||||
userRepository.count();
|
||||
userRepository.existsById(3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomSql() {
|
||||
userRepository.modifyById("neo",3L);
|
||||
userRepository.deleteById(3L);
|
||||
userRepository.findByEmail("ff@126.com");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testPageQuery() {
|
||||
int page=1,size=2;
|
||||
Sort sort = new Sort(Sort.Direction.DESC, "id");
|
||||
Pageable pageable = PageRequest.of(page, size, sort);
|
||||
userRepository.findALL(pageable);
|
||||
userRepository.findByNickName("aa", pageable);
|
||||
}
|
||||
|
||||
}
|
||||
52
spring-boot-jpa/spring-boot-multi-Jpa/pom.xml
Normal file
52
spring-boot-jpa/spring-boot-multi-Jpa/pom.xml
Normal file
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
|
||||
<groupId>com.neo</groupId>
|
||||
<artifactId>spring-boot-multi-Jpa</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>spring-boot-multi-Jpa</name>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.0.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.neo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class MultiJpaApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MultiJpaApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.neo.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
|
||||
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
|
||||
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
public class DataSourceConfig {
|
||||
|
||||
@Autowired
|
||||
private JpaProperties jpaProperties;
|
||||
@Autowired
|
||||
private HibernateProperties hibernateProperties;
|
||||
|
||||
@Bean(name = "primaryDataSource")
|
||||
@Primary
|
||||
@ConfigurationProperties("spring.datasource.primary")
|
||||
public DataSource firstDataSource() {
|
||||
return DataSourceBuilder.create().build();
|
||||
}
|
||||
|
||||
@Bean(name = "secondaryDataSource")
|
||||
@ConfigurationProperties("spring.datasource.secondary")
|
||||
public DataSource secondDataSource() {
|
||||
return DataSourceBuilder.create().build();
|
||||
}
|
||||
|
||||
@Bean(name = "vendorProperties")
|
||||
public Map<String, Object> getVendorProperties() {
|
||||
return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.neo.config;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(
|
||||
entityManagerFactoryRef="entityManagerFactoryPrimary",
|
||||
transactionManagerRef="transactionManagerPrimary",
|
||||
basePackages= { "com.neo.repository.test1" })//设置dao(repo)所在位置
|
||||
public class PrimaryConfig {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("primaryDataSource")
|
||||
private DataSource primaryDataSource;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("vendorProperties")
|
||||
private Map<String, Object> vendorProperties;
|
||||
|
||||
@Bean(name = "entityManagerFactoryPrimary")
|
||||
@Primary
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
|
||||
return builder
|
||||
.dataSource(primaryDataSource)
|
||||
.properties(vendorProperties)
|
||||
.packages("com.neo.model") //设置实体类所在位置
|
||||
.persistenceUnit("primaryPersistenceUnit")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean(name = "entityManagerPrimary")
|
||||
@Primary
|
||||
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
|
||||
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
|
||||
}
|
||||
|
||||
@Bean(name = "transactionManagerPrimary")
|
||||
@Primary
|
||||
PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
|
||||
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.neo.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(
|
||||
entityManagerFactoryRef="entityManagerFactorySecondary",
|
||||
transactionManagerRef="transactionManagerSecondary",
|
||||
basePackages= { "com.neo.repository.test2" })
|
||||
public class SecondaryConfig {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("secondaryDataSource")
|
||||
private DataSource secondaryDataSource;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("vendorProperties")
|
||||
private Map<String, Object> vendorProperties;
|
||||
|
||||
@Bean(name = "entityManagerFactorySecondary")
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
|
||||
return builder
|
||||
.dataSource(secondaryDataSource)
|
||||
.properties(vendorProperties)
|
||||
.packages("com.neo.model")
|
||||
.persistenceUnit("secondaryPersistenceUnit")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean(name = "entityManagerSecondary")
|
||||
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
|
||||
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
|
||||
}
|
||||
|
||||
@Bean(name = "transactionManagerSecondary")
|
||||
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
|
||||
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.neo.model;
|
||||
|
||||
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
public class User implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
@Column(nullable = false, unique = true)
|
||||
private String userName;
|
||||
@Column(nullable = false)
|
||||
private String passWord;
|
||||
@Column(nullable = false, unique = true)
|
||||
private String email;
|
||||
@Column(nullable = true, unique = true)
|
||||
private String nickName;
|
||||
@Column(nullable = false)
|
||||
private String regTime;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String userName, String passWord, String email, String nickName, String regTime) {
|
||||
this.userName = userName;
|
||||
this.passWord = passWord;
|
||||
this.email = email;
|
||||
this.nickName = nickName;
|
||||
this.regTime = regTime;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public String getPassWord() {
|
||||
return passWord;
|
||||
}
|
||||
|
||||
public void setPassWord(String passWord) {
|
||||
this.passWord = passWord;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getNickName() {
|
||||
return nickName;
|
||||
}
|
||||
|
||||
public void setNickName(String nickName) {
|
||||
this.nickName = nickName;
|
||||
}
|
||||
|
||||
public String getRegTime() {
|
||||
return regTime;
|
||||
}
|
||||
|
||||
public void setRegTime(String regTime) {
|
||||
this.regTime = regTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.neo.repository.test1;
|
||||
|
||||
import com.neo.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserTest1Repository extends JpaRepository<User, Long> {
|
||||
User findById(long id);
|
||||
User findByUserName(String userName);
|
||||
User findByUserNameOrEmail(String username, String email);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.neo.repository.test2;
|
||||
|
||||
import com.neo.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
|
||||
public interface UserTest2Repository extends JpaRepository<User, Long> {
|
||||
User findById(long id);
|
||||
User findByUserName(String userName);
|
||||
User findByUserNameOrEmail(String username, String email);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
|
||||
spring.datasource.primary.username=root
|
||||
spring.datasource.primary.password=root
|
||||
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
|
||||
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
|
||||
spring.datasource.secondary.username=root
|
||||
spring.datasource.secondary.password=root
|
||||
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
|
||||
#sql\u8F93\u51FA
|
||||
spring.jpa.show-sql=true
|
||||
spring.jpa.properties.hibernate.hbm2ddl.auto=create
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
|
||||
#format\u4E00\u4E0Bsql\u8FDB\u884C\u8F93\u51FA
|
||||
spring.jpa.properties.hibernate.format_sql=true
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.neo;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class MultiJpaApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() {
|
||||
System.out.println("Hello MultiJpa!");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.neo.repository;
|
||||
|
||||
import com.neo.model.User;
|
||||
import com.neo.repository.test1.UserTest1Repository;
|
||||
import com.neo.repository.test2.UserTest2Repository;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.text.DateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class UserRepositoryTests {
|
||||
@Resource
|
||||
private UserTest1Repository userTest1Repository;
|
||||
@Resource
|
||||
private UserTest2Repository userTest2Repository;
|
||||
|
||||
@Test
|
||||
public void testSave() throws Exception {
|
||||
Date date = new Date();
|
||||
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
|
||||
String formattedDate = dateFormat.format(date);
|
||||
|
||||
userTest1Repository.save(new User("aa", "aa123456","aa@126.com", "aa", formattedDate));
|
||||
userTest1Repository.save(new User("bb", "bb123456","bb@126.com", "bb", formattedDate));
|
||||
userTest2Repository.save(new User("cc", "cc123456","cc@126.com", "cc", formattedDate));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDelete() throws Exception {
|
||||
userTest1Repository.deleteAll();
|
||||
userTest2Repository.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBaseQuery() {
|
||||
Date date = new Date();
|
||||
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
|
||||
String formattedDate = dateFormat.format(date);
|
||||
User user=new User("ff", "ff123456","ff@126.com", "ff", formattedDate);
|
||||
userTest1Repository.findAll();
|
||||
userTest2Repository.findById(3l);
|
||||
userTest2Repository.save(user);
|
||||
user.setId(2l);
|
||||
userTest1Repository.delete(user);
|
||||
userTest1Repository.count();
|
||||
userTest2Repository.findById(3l);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user