From 8de7f6bbbae9267d079c8f93cbfa03467e0477a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BA=AF=E6=B4=81=E7=9A=84=E5=BE=AE=E7=AC=91?= Date: Sat, 9 Mar 2019 22:46:53 +0800 Subject: [PATCH] add jpa examples --- spring-boot-jpa/spring-boot-jpa/pom.xml | 52 +++++++++ .../src/main/java/com/neo/JpaApplication.java | 13 +++ .../src/main/java/com/neo/model/Address.java | 59 ++++++++++ .../src/main/java/com/neo/model/User.java | 87 +++++++++++++++ .../main/java/com/neo/model/UserDetail.java | 102 ++++++++++++++++++ .../src/main/java/com/neo/model/UserInfo.java | 8 ++ .../java/com/neo/param/UserDetailParam.java | 65 +++++++++++ .../com/neo/repository/AddressRepository.java | 7 ++ .../neo/repository/UserDetailRepository.java | 20 ++++ .../com/neo/repository/UserRepository.java | 40 +++++++ .../com/neo/service/UserDetailService.java | 10 ++ .../neo/service/UserDetailServiceImpl.java | 48 +++++++++ .../src/main/resources/application.properties | 11 ++ .../java/com/neo/JpaApplicationTests.java | 16 +++ .../neo/repository/JpaSpecificationTests.java | 40 +++++++ .../repository/UserDetailRepositoryTests.java | 59 ++++++++++ .../neo/repository/UserRepositoryTests.java | 71 ++++++++++++ spring-boot-jpa/spring-boot-multi-Jpa/pom.xml | 52 +++++++++ .../java/com/neo/MultiJpaApplication.java | 12 +++ .../java/com/neo/config/DataSourceConfig.java | 41 +++++++ .../java/com/neo/config/PrimaryConfig.java | 59 ++++++++++ .../java/com/neo/config/SecondaryConfig.java | 54 ++++++++++ .../src/main/java/com/neo/model/User.java | 86 +++++++++++++++ .../repository/test1/UserTest1Repository.java | 10 ++ .../repository/test2/UserTest2Repository.java | 11 ++ .../src/main/resources/application.properties | 16 +++ .../com/neo/MultiJpaApplicationTests.java | 18 ++++ .../neo/repository/UserRepositoryTests.java | 58 ++++++++++ 28 files changed, 1125 insertions(+) create mode 100644 spring-boot-jpa/spring-boot-jpa/pom.xml create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/JpaApplication.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/Address.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/User.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/UserDetail.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/UserInfo.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/param/UserDetailParam.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/AddressRepository.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/UserDetailRepository.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/UserRepository.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/service/UserDetailService.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/service/UserDetailServiceImpl.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/main/resources/application.properties create mode 100644 spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/JpaApplicationTests.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/JpaSpecificationTests.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/UserDetailRepositoryTests.java create mode 100644 spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/UserRepositoryTests.java create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/pom.xml create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/MultiJpaApplication.java create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/DataSourceConfig.java create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/PrimaryConfig.java create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/SecondaryConfig.java create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/model/User.java create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/repository/test1/UserTest1Repository.java create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/repository/test2/UserTest2Repository.java create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/main/resources/application.properties create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/test/java/com/neo/MultiJpaApplicationTests.java create mode 100644 spring-boot-jpa/spring-boot-multi-Jpa/src/test/java/com/neo/repository/UserRepositoryTests.java diff --git a/spring-boot-jpa/spring-boot-jpa/pom.xml b/spring-boot-jpa/spring-boot-jpa/pom.xml new file mode 100644 index 0000000..b42ead5 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + com.neo + spring-boot-Jpa + 1.0.0 + jar + + spring-boot-Jpa + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.1.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/JpaApplication.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/JpaApplication.java new file mode 100644 index 0000000..a1b5532 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/JpaApplication.java @@ -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); + } +} diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/Address.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/Address.java new file mode 100644 index 0000000..883ea20 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/Address.java @@ -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; + } +} diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/User.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/User.java new file mode 100644 index 0000000..7ec1e8b --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/User.java @@ -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; + } +} diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/UserDetail.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/UserDetail.java new file mode 100644 index 0000000..4f3c67d --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/UserDetail.java @@ -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 + '\'' + + '}'; + } +} diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/UserInfo.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/UserInfo.java new file mode 100644 index 0000000..5a5ae5e --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/model/UserInfo.java @@ -0,0 +1,8 @@ +package com.neo.model; + +public interface UserInfo { + String getUserName(); + String getEmail(); + String getHobby(); + String getIntroduction(); +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/param/UserDetailParam.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/param/UserDetailParam.java new file mode 100644 index 0000000..0f7a497 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/param/UserDetailParam.java @@ -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; + } +} diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/AddressRepository.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/AddressRepository.java new file mode 100644 index 0000000..3bba027 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/AddressRepository.java @@ -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 { +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/UserDetailRepository.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/UserDetailRepository.java new file mode 100644 index 0000000..e133b05 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/UserDetailRepository.java @@ -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,JpaRepository { + + 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 findUserInfo(String hobby); +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/UserRepository.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/UserRepository.java new file mode 100644 index 0000000..8318068 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/repository/UserRepository.java @@ -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 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 findALL(Pageable pageable); + + Page findByNickName(String nickName, Pageable pageable); + + Slice findByNickNameAndEmail(String nickName, String email,Pageable pageable); + + +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/service/UserDetailService.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/service/UserDetailService.java new file mode 100644 index 0000000..a5d14ea --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/service/UserDetailService.java @@ -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 findByCondition(UserDetailParam detailParam, Pageable pageable); +} diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/service/UserDetailServiceImpl.java b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/service/UserDetailServiceImpl.java new file mode 100644 index 0000000..18eaba9 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/java/com/neo/service/UserDetailServiceImpl.java @@ -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 findByCondition(UserDetailParam detailParam, Pageable pageable){ + + return userDetailRepository.findAll((root, query, cb) -> { + List predicates = new ArrayList(); + //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); + + } +} diff --git a/spring-boot-jpa/spring-boot-jpa/src/main/resources/application.properties b/spring-boot-jpa/spring-boot-jpa/src/main/resources/application.properties new file mode 100644 index 0000000..b0b5ebe --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/main/resources/application.properties @@ -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 \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/JpaApplicationTests.java b/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/JpaApplicationTests.java new file mode 100644 index 0000000..4fe4fdb --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/JpaApplicationTests.java @@ -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() { + } + +} diff --git a/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/JpaSpecificationTests.java b/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/JpaSpecificationTests.java new file mode 100644 index 0000000..751b7d3 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/JpaSpecificationTests.java @@ -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 page1=userDetailService.findByCondition(param,pageable); + for (UserDetail userDetail:page1){ + System.out.println("userDetail: "+userDetail.toString()); + } + } + +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/UserDetailRepositoryTests.java b/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/UserDetailRepositoryTests.java new file mode 100644 index 0000000..679efb1 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/UserDetailRepositoryTests.java @@ -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 userInfos=userDetailRepository.findUserInfo("钓鱼"); + for (UserInfo userInfo:userInfos){ + System.out.println("userInfo: "+userInfo.getUserName()+"-"+userInfo.getEmail()+"-"+userInfo.getHobby()+"-"+userInfo.getIntroduction()); + } + } +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/UserRepositoryTests.java b/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/UserRepositoryTests.java new file mode 100644 index 0000000..c689ce5 --- /dev/null +++ b/spring-boot-jpa/spring-boot-jpa/src/test/java/com/neo/repository/UserRepositoryTests.java @@ -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); + } + +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/pom.xml b/spring-boot-jpa/spring-boot-multi-Jpa/pom.xml new file mode 100644 index 0000000..78e5e2e --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + com.neo + spring-boot-multi-Jpa + 1.0 + jar + + spring-boot-multi-Jpa + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.1.0.RELEASE + + + + + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/MultiJpaApplication.java b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/MultiJpaApplication.java new file mode 100644 index 0000000..2a9a26b --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/MultiJpaApplication.java @@ -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); + } +} diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/DataSourceConfig.java b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/DataSourceConfig.java new file mode 100644 index 0000000..09f2b75 --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/DataSourceConfig.java @@ -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 getVendorProperties() { + return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()); + } +} diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/PrimaryConfig.java b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/PrimaryConfig.java new file mode 100644 index 0000000..588cf91 --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/PrimaryConfig.java @@ -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 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()); + } + +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/SecondaryConfig.java b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/SecondaryConfig.java new file mode 100644 index 0000000..241f476 --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/config/SecondaryConfig.java @@ -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 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()); + } + +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/model/User.java b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/model/User.java new file mode 100644 index 0000000..f4cb974 --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/model/User.java @@ -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; + } +} diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/repository/test1/UserTest1Repository.java b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/repository/test1/UserTest1Repository.java new file mode 100644 index 0000000..feeccea --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/repository/test1/UserTest1Repository.java @@ -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 findById(long id); + User findByUserName(String userName); + User findByUserNameOrEmail(String username, String email); +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/repository/test2/UserTest2Repository.java b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/repository/test2/UserTest2Repository.java new file mode 100644 index 0000000..45f8c24 --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/java/com/neo/repository/test2/UserTest2Repository.java @@ -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 findById(long id); + User findByUserName(String userName); + User findByUserNameOrEmail(String username, String email); +} \ No newline at end of file diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/main/resources/application.properties b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/resources/application.properties new file mode 100644 index 0000000..cab7dd7 --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/main/resources/application.properties @@ -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 diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/test/java/com/neo/MultiJpaApplicationTests.java b/spring-boot-jpa/spring-boot-multi-Jpa/src/test/java/com/neo/MultiJpaApplicationTests.java new file mode 100644 index 0000000..c87999c --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/test/java/com/neo/MultiJpaApplicationTests.java @@ -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!"); + } + +} diff --git a/spring-boot-jpa/spring-boot-multi-Jpa/src/test/java/com/neo/repository/UserRepositoryTests.java b/spring-boot-jpa/spring-boot-multi-Jpa/src/test/java/com/neo/repository/UserRepositoryTests.java new file mode 100644 index 0000000..693986f --- /dev/null +++ b/spring-boot-jpa/spring-boot-multi-Jpa/src/test/java/com/neo/repository/UserRepositoryTests.java @@ -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); + } + + +} \ No newline at end of file