当前位置: 代码网 > it编程>编程语言>Java > SpringBoot整合JPA详细代码实例

SpringBoot整合JPA详细代码实例

2024年06月12日 Java 我要评论
1、spring data jpa概述springdata:spring 的一个子项目。用于简化数据库访问,支持nosql 和 关系数据存储。其主要目标是使数据库的访问变得方便快捷。jpa:jpa(j

1、spring data jpa概述

springdata:spring 的一个子项目。用于简化数据库访问,支持nosql 和 关系数据存储。其主要目标是使数据

库的访问变得方便快捷。

jpa:jpa(java persistence api,java持久化api),定义了对象关系映射(object relation mapping,orm)以及实

体对象持久化的标准接口。hibernate实现了jpa的一个orm框架。

jpa spring data:致力于减少数据访问层 (dao) 的开发量,开发者唯一要做的,就只是声明持久层的接口,

其他都交给 spring data jpa 来完成。spring data jpa 是spring基于orm框架、jpa规范的基础上封装的一套jpa

应用框架。

2、springboot整合jpa

2.1 建库建表

drop table if exists  student ;
create table  student  (
   id  int(11) not null auto_increment,
   name  varchar(100) default null,
   sex  varchar(100) default null,
   age  int(11) default null,
  primary key ( id )
) engine=innodb auto_increment=1 default charset=utf8;

2.2 新建项目

目录结构如下:

2.3 添加相关依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelversion>4.0.0</modelversion>
	<parent>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-parent</artifactid>
		<version>2.5.4</version>
		<relativepath/>
	</parent>
	<groupid>com.jpa.mysql</groupid>
	<artifactid>spring-data-jpa-mysql</artifactid>
	<version>0.0.1-snapshot</version>
	<name>spring-data-jpa-mysql</name>
	<description>spring-data-jpa-mysql</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-web</artifactid>
		</dependency>

		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter</artifactid>
		</dependency>

		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-test</artifactid>
			<scope>test</scope>
		</dependency>

		<!-- jpa 依赖-->
		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-data-jpa</artifactid>
		</dependency>

		<!-- lombok 依赖-->
		<dependency>
			<groupid>org.projectlombok</groupid>
			<artifactid>lombok</artifactid>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupid>mysql</groupid>
			<artifactid>mysql-connector-java</artifactid>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupid>org.springframework.boot</groupid>
				<artifactid>spring-boot-maven-plugin</artifactid>
			</plugin>
		</plugins>
	</build>

</project>

2.4 修改application.properties配置文件

server.port=9000
spring.datasource.driver-class-name=com.mysql.jdbc.driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.mysql5dialect

2.5 编写entity

package com.jpa.mysql.entity;

import lombok.data;

import javax.persistence.column;
import javax.persistence.entity;
import javax.persistence.id;
import javax.persistence.table;
import java.io.serializable;

@data
@entity
@table(name = "student")
public class student implements serializable {

    @id
    @column(name="id")
    private int id;

    @column(name="name")
    private string name;

    @column(name="sex")
    private string sex;

    @column(name="age")
    private int age;
}

2.6 编写dao

package com.jpa.gbase.dao;

import com.jpa.gbase.entity.student;
import org.springframework.data.jpa.repository.jparepository;
import org.springframework.stereotype.repository;

import java.util.list;

@repository
public interface studentdao extends jparepository<student, integer> {

    list<student> findbyname(string name);
}

2.6 编写service接口

package com.jpa.gbase.service;
import com.jpa.gbase.entity.student;
import org.springframework.stereotype.component;
import java.util.list;
@component
public interface istudentservice {
    student findbyid(integer id);
    list<student> findall();
    list<student> findbyname(string name);
    student save(string name) throws exception;
    void delete(integer id) throws exception;
}

2.7 编写service实现类

package com.jpa.gbase.service.impl;

import com.jpa.gbase.dao.studentdao;
import com.jpa.gbase.entity.student;
import com.jpa.gbase.service.istudentservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.component;
import org.springframework.transaction.annotation.transactional;

import java.util.list;

@component
public class studentserviceimpl implements istudentservice {

    @autowired
    private studentdao studentdao;

    @override
    public student findbyid(integer id) {
        return studentdao.findbyid(id).get();
    }

    @override
    public list<student> findall() {
        return studentdao.findall();
    }

    @override
    public list<student> findbyname(string name) {
        return studentdao.findbyname(name);
    }

    @override
    @transactional
    public student save(string name) throws exception {
        student student = new student();
        student.setname(name);
        student.setsex("m");
        student.setage(18);
        return studentdao.save(student);
    }

    @override
    @transactional
    public void delete(integer id) throws exception {
        studentdao.deletebyid(id);
    }
}

2.8 编写controller

package com.jpa.gbase.controller;

import com.jpa.gbase.entity.student;
import com.jpa.gbase.service.istudentservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.restcontroller;

import java.util.list;

@restcontroller
@requestmapping(value = "/student")
public class studentcontroller {

    @autowired
    private istudentservice studentservice;

    @getmapping(value = "/findbyid/{id}")
    public student findbyid(@pathvariable("id") integer id) {
        return studentservice.findbyid(id);
    }

    @getmapping(value = "/findall")
    public list<student> findall() {
        return studentservice.findall();
    }

    @getmapping(value = "/findbyname/{name}")
    public list<student> findbyname(@pathvariable("name") string name) {
        return studentservice.findbyname(name);
    }

    @getmapping(value = "/save/{name}")
    public student save(@pathvariable("name") string name) {
        student student = new student();
        try {
            student = studentservice.save(name);
        } catch (exception e) {
            e.printstacktrace();
        }
        return student;

    }

    @getmapping(value = "/delete/{id}")
    public boolean delete(@pathvariable("id") integer id) {
        boolean flg = false;
        try {
            studentservice.delete(id);
            flg = true;
        } catch (exception e) {
            e.printstacktrace();
        }
        return flg;
    }

}

2.9 编写启动类

package com.jpa.mysql;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;

@springbootapplication
public class springdatajpamysqlapplication {

	public static void main(string[] args) {

		springapplication.run(springdatajpamysqlapplication.class, args);
	}

}

3.测试

3.1 添加数据

http://localhost:9000/student/save/tom

3.2 根据id查询数据

http://localhost:9000/student/findbyid/1

3.3 根据名字查询数据

http://localhost:9000/student/findbyname/tom

3.4 根据id删除数据

http://localhost:9000/student/delete/1

在这里插入图片描述

3.5 查询全部数据

http://localhost:9000/student/save/tom1
http://localhost:9000/student/save/tom2
http://localhost:9000/student/save/tom3
http://localhost:9000/student/save/tom4
http://localhost:9000/student/save/tom5
http://localhost:9000/student/findall

4、简单查询

基本查询也分为两种,一种是 spring data 默认已经实现,一种是根据查询的方法来自动解析成 sql。

4.1 预先生成方法

spring boot jpa 默认预先生成了一些基本的curd的方法,例如:增、删、改等等

1、继承 jparepository

@repository
public interface studentdao extends jparepository<student, integer> {
}

2、使用默认方法

@autowired
private studentdao studentdao;

studentdao.findall();
studentdao.findone(1l);
studentdao.save(user);
studentdao.delete(user);
studentdao.count();
studentdao.exists(1l);

4.2 自定义简单查询

自定义的简单查询就是根据方法名来自动生成 sql。

主要的语法是 findbyxx,readabyxx,querybyxx,countbyxxgetbyxx xx 代表属性名称。

student findbyname(string name);

也使用一些加一些关键字and 、 or

user findbynameorsex(string username, int sex);

修改、删除、统计也是类似语法:

long deletebyid(long id);
long countbyname(string mame);

基本上 sql 体系中的关键词都可以使用,例如:like、 ignorecase、 orderby

list<student> findbynamelike(string name);
student findbynameignorecase(string name);
list<student> findbynameorderbyagedesc(string name);

具体的关键字,使用方法和生产成sql如下表所示:

keywordsamplejpql snippet
andfindbylastnameandfirstname… where x.lastname = ?1 and x.firstname = ?2
orfindbylastnameorfirstname… where x.lastname = ?1 or x.firstname = ?2
is,equalsfindbyfirstnameis,findbyfirstnameequals… where x.firstname = ?1
betweenfindbystartdatebetween… where x.startdate between ?1 and ?2
lessthanfindbyagelessthan… where x.age < ?1
lessthanequalfindbyagelessthanequal… where x.age <= ?1
greaterthanfindbyagegreaterthan… where x.age > ?1
greaterthanequalfindbyagegreaterthanequal… where x.age >= ?1
afterfindbystartdateafter… where x.startdate > ?1
beforefindbystartdatebefore… where x.startdate < ?1
isnullfindbyageisnull… where x.age is null
isnotnull,notnullfindbyage(is)notnull… where x.age not null
likefindbyfirstnamelike… where x.firstname like ?1
notlikefindbyfirstnamenotlike… where x.firstname not like ?1
startingwithfindbyfirstnamestartingwith… where x.firstname like ?1 (parameter bound with appended %)
endingwithfindbyfirstnameendingwith… where x.firstname like ?1 (parameter bound with prepended %)
containingfindbyfirstnamecontaining… where x.firstname like ?1 (parameter bound wrapped in %)
orderbyfindbyageorderbylastnamedesc… where x.age = ?1 order by x.lastname desc
notfindbylastnamenot… where x.lastname <> ?1
infindbyagein(collection ages)… where x.age in ?1
notinfindbyagenotin(collection age)… where x.age not in ?1
truefindbyactivetrue()… where x.active = true
falsefindbyactivefalse()… where x.active = false
ignorecasefindbyfirstnameignorecase… where upper(x.firstame) = upper(?1)

5、复杂查询

在实际的开发中我们需要用到分页、删选、连表等查询的时候就需要特殊的方法或者自定义 sql。

5.1 分页查询

分页查询在实际使用中非常普遍了,spring boot jpa 已经帮我们实现了分页的功能,在查询的方法中,需要传入

参数pageable ,当查询中有多个参数的时候pageable建议做为最后一个参数传入。

page<student> findall(pageable pageable);
page<student> findbyname(string name,pageable pageable);

pageable 是 spring 封装的分页实现类,使用的时候需要传入页数、每页条数和排序规则。

@test
public void testpagequery() throws exception {
	int page=1,size=10;
	sort sort = new sort(direction.desc, "id");
    pageable pageable = new pagerequest(page, size, sort);
    studentdao.findall(pageable);
    studentdao.findbyname("tom", pageable);
}

5.2 限制查询

有时候我们只需要查询前n个元素,或者只取前一个实体。

student findfirstbyorderbynameasc();
student findtopbyorderbyagedesc();
page&lt;student&gt; queryfirst10byname(string name, pageable pageable);
list&lt;student&gt; findfirst10byname(string name, sort sort);
list&lt;student&gt; findtop10byname(string name, pageable pageable);

5.3 自定义sql查询

其实 spring data 觉大部分的 sql 都可以根据方法名定义的方式来实现,但是由于某些原因我们想使用自定义的

sql 来查询,spring data 也是完美支持的;在 sql 的查询方法上面使用@query注解,如涉及到删除和修改再需

要加上@modifying,也可以根据需要添加 @transactional对事物的支持,查询超时的设置等。

@modifying
@query("update student stu set stu.name = ?1 where stu.id = ?2")
int modifynamebyid(string name, long id);
	
@transactional
@modifying
@query("delete from student where id = ?1")
void deletebyid(long id);

@transactional(timeout = 10)
@query("select stu from student stu where stu.id = ?1")
user findbyid(long id);

5.4 多表查询

多表查询 spring boot jpa 中有两种实现方式,第一种是利用 hibernate 的级联查询来实现,第二种是创建一个结

果集的接口来接收连表查询后的结果,这里主要第二种方式。

首先需要定义一个结果集的接口类:

public interface hotelsummary {
	city getcity();
	string getname();
	double getaveragerating();
	default integer getaverageratingrounded() {
		return getaveragerating() == null ? null : (int) math.round(getaveragerating());
	}
}

查询的方法返回类型设置为新创建的接口:

@query("select h.city as city, h.name as name, avg(r.rating) as averagerating "
		- "from hotel h left outer join h.reviews r where h.city = ?1 group by h")
page<hotelsummary> findbycity(city city, pageable pageable);

@query("select h.name as name, avg(r.rating) as averagerating "
		- "from hotel h left outer join h.reviews r  group by h")
page<hotelsummary> findbycity(pageable pageable);

使用:

page<hotelsummary> hotels = this.hotelrepository.findbycity(new pagerequest(0, 10, direction.asc, "name"));
for(hotelsummary summay:hotels){
		system.out.println("name" +summay.getname());
	}

在运行中 spring 会给接口(hotelsummary)自动生产一个代理类来接收返回的结果,代码汇总使用 getxx

的形式来获取。

6、使用枚举

使用枚举的时候,我们希望数据库中存储的是枚举对应的 string 类型,而不是枚举的索引值,需要在属性上面添

@enumerated(enumtype.string) 注解

@enumerated(enumtype.string) 
@column(nullable = true)
private usertype type;

7、不需要和数据库映射的属性

正常情况下我们在实体类上加入注解@entity,就会让实体类和表相关连如果其中某个属性我们不需要和数据库

来关联只是在展示的时候做计算,只需要加上@transient属性既可。

@transient
private string username;

8、多数据源的支持

8.1 同源数据库的多源支持

日常项目中因为使用的分布式开发模式,不同的服务有不同的数据源,常常需要在一个项目中使用多个数据源,因

此需要配置 spring boot jpa 对多数据源的使用,一般分一下为三步:

  • 1 配置多数据源

  • 2 不同源的实体类放入不同包路径

  • 3 声明不同的包路径下使用不同的数据源、事务支持

8.2 异构数据库多源支持

比如我们的项目中,即需要对 mysql 的支持,也需要对 mongodb 的查询等。

实体类声明@entity 关系型数据库支持类型,声明@document 为 mongodb 支持类型,不同的数据源使用不同的

实体就可以了。

interface personrepository extends repository<person, long> {
 …
}

@entity
public class person {
  …
}

interface userrepository extends repository<user, long> {
 …
}

@document
public class user {
  …
}

但是,如果 user 用户既使用 mysql 也使用 mongodb 呢,也可以做混合使用。

interface jpapersonrepository extends repository<person, long> {
 …
}

interface mongodbpersonrepository extends repository<person, long> {
 …
}

@entity
@document
public class person {
  …
}

也可以通过对不同的包路径进行声明,比如 a 包路径下使用 mysql,b 包路径下使用 mongodb。

@enablejparepositories(basepackages = "com.neo.repositories.jpa")
@enablemongorepositories(basepackages = "com.neo.repositories.mongo")
interface configuration { }

9、多数据源使用案例

9.1 导入pom依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelversion>4.0.0</modelversion>
    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>2.5.4</version>
        <relativepath/>
    </parent>

    <groupid>com.example</groupid>
    <artifactid>spring-boot-multi-jpa</artifactid>
    <version>0.0.1-snapshot</version>
    <name>spring-boot-multi-jpa</name>
    <description>spring-boot-multi-jpa</description>

    <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-web</artifactid>
        </dependency>

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter</artifactid>
        </dependency>

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-test</artifactid>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-data-jpa</artifactid>
        </dependency>

        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
        </dependency>

        <!-- lombok 依赖-->
        <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupid>junit</groupid>
            <artifactid>junit</artifactid>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-maven-plugin</artifactid>
            </plugin>
        </plugins>
    </build>

</project>

9.2 配置文件

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

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.hbm2ddl.auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.mysql5innodbdialect
spring.jpa.properties.hibernate.format_sql=true

9.3 实体类

package com.example.springbootmultijpa.model;

import lombok.allargsconstructor;
import lombok.getter;
import lombok.noargsconstructor;
import lombok.setter;

import javax.persistence.*;
import java.io.serializable;

@getter
@setter
@entity
@noargsconstructor
@allargsconstructor
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(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;
    }
}

9.4 config

package com.example.springbootmultijpa.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());
    }
}
package com.example.springbootmultijpa.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.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;

import javax.persistence.entitymanager;
import javax.sql.datasource;
import java.util.map;

@configuration
@enabletransactionmanagement
@enablejparepositories(
        entitymanagerfactoryref = "entitymanagerfactoryprimary",
        transactionmanagerref = "transactionmanagerprimary",
        basepackages = {"com.example.springbootmultijpa.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.example.springbootmultijpa.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());
    }

}
package com.example.springbootmultijpa.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.example.springbootmultijpa.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.example.springbootmultijpa.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());
    }

}

9.5 repository

package com.example.springbootmultijpa.repository.test1;

import com.example.springbootmultijpa.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);
}
package com.example.springbootmultijpa.repository.test2;

import com.example.springbootmultijpa.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);
}

9.6 启动类

package com.example.springbootmultijpa;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;

@springbootapplication
public class springbootmultijpaapplication {

    public static void main(string[] args) {

        springapplication.run(springbootmultijpaapplication.class, args);
    }
}

9.7 测试

package com.example.springbootmultijpa.repository;

import com.example.springbootmultijpa.model.user;
import com.example.springbootmultijpa.repository.test1.usertest1repository;
import com.example.springbootmultijpa.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 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);
    }
}

运行testsave()得到的结果:

运行testbasequery()得到的结果:

运行testdelete()得到的结果:

总结

到此这篇关于springboot整合jpa的文章就介绍到这了,更多相关springboot整合jpa内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com