Spring Boot整合Spring Data JPA
2021-01-16 10:14
标签:split 能力 listen usr 方法调用 根据 首字母 nes jdbc 首先说明一下,这里使用的是Springboot2.2.6.RELEASE版本,由于Springboot迭代很快,所以要注意版本问题。 1、Spring Data是Spring提供的帮助操作数据的框架,Spring Data中的一个模块叫做Spring Data JPA,Spring Data JPA只是Spring Data框架下的一个基于JPA标准操作数据的模块,Spring Data JPA底层默认的使用的是Hibernate来做的JPA实现。Spring Data JPA核心能力就是基于JPA的标准对数据进行操作,极大简化了代码的编写,简化操作持久层的代码,直接编写接口就可以了。 在application.properties配置文件中配置数据库链接信息、数据库链接池、Spring Data JPA开启正向工程、在控制台打印sql语句。 创建实体类Users。 创建数据交互层接口继承JpaRepository 泛型参数1,T表示的是当前需要映射的实体类类型,当前需要映射的实体。 泛型参数2,ID表示需要映射的实体中的主键的类型,当前映射的实体中的OID的类型。 开始测试,测试代码,如下所示: 如果下面报错,就在数据库链接URL后面根据下面所示的内容即可。 ?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC 2、Spring Data JPA提供的核心接口。 2.1)、Repository接口,提供了方法名称命名查询方式。
测试代码,如下所示: Repository接口,提供了基于@Query注解的查询与更新方式。 测试代码,如下所示: 如果报如下所示的错误,需要将@Query(value = "from Users where name = ?")修改为@Query(value = "from Users where name = :name")。 1 "1.0" encoding="UTF-8"?>
2
1 # mysql的数据库驱动
2 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3 # mysql的链接
4 spring.datasource.url=jdbc:mysql://localhost:3306/ssm
5 # mysql的账号
6 spring.datasource.username=root
7 # mysql的密码
8 spring.datasource.password=123456
9
10 # druid连接池的配置
11 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
12
13 # Spring Data JPA,此配置可以在实体类中使用注解来创建数据表,开启正向工程
14 spring.jpa.hibernate.ddl-auto=update
15 # 在控制台打印sql语句
16 spring.jpa.show-sql=true
1 package com.bie.springboot.po;
2
3 import javax.persistence.*;
4
5 @Entity // 表示该类是实体类
6 @Table(name = "tb_users") // 表示该实体类和数据表进行映射,name表示实体类和数据表进行映射
7 // 如果使用的是正向工程的话,name属性的值表示的是数据表的表名称。
8 public class Users {
9
10 @Id // 表示该字段是主键
11 @GeneratedValue(strategy = GenerationType.IDENTITY) // 主键的生成策略
12 @Column(name = "id") // 表示实体类的字段和数据表的字段进行映射的关系,如果是正向工程的话,name的值就是数据表的字段名称
13 private Integer id;// 用户编号
14
15 @Column(name = "name")
16 private String name;// 用户姓名
17
18 @Column(name = "age")
19 private Integer age;// 用户年龄
20
21 @Column(name = "address")
22 private String address;// 用户地址
23
24 // alt + insert来生成构造器、setter\getter等等方法
25 public Integer getId() {
26 return id;
27 }
28
29 public void setId(Integer id) {
30 this.id = id;
31 }
32
33 public String getName() {
34 return name;
35 }
36
37 public void setName(String name) {
38 this.name = name;
39 }
40
41 public Integer getAge() {
42 return age;
43 }
44
45 public void setAge(Integer age) {
46 this.age = age;
47 }
48
49 public String getAddress() {
50 return address;
51 }
52
53 public void setAddress(String address) {
54 this.address = address;
55 }
56
57 @Override
58 public String toString() {
59 return "Users{" +
60 "id=" + id +
61 ", name=‘" + name + ‘\‘‘ +
62 ", age=" + age +
63 ", address=‘" + address + ‘\‘‘ +
64 ‘}‘;
65 }
66
67 public Users(String name, Integer age, String address) {
68 this.name = name;
69 this.age = age;
70 this.address = address;
71 }
72
73 public Users() {
74 }
75 }
1 package com.bie.springboot.dao;
2
3 import com.bie.springboot.po.Users;
4 import org.springframework.data.jpa.repository.JpaRepository;
5
6 /**
7 * JpaRepository
1 package com.bie.springboot;
2
3 import com.bie.springboot.dao.UsersDao;
4 import com.bie.springboot.po.Users;
5 import org.junit.jupiter.api.Test;
6 import org.junit.runner.RunWith;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.boot.test.context.SpringBootTest;
9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10
11 @RunWith(SpringJUnit4ClassRunner.class)
12 @SpringBootTest(classes = SpringbootJpaApplication.class) // 启动器,将测试类和启动器整合在一起
13 class SpringbootJpaApplicationTests {
14
15 @Autowired
16 private UsersDao usersDao;
17
18 @Test
19 public void testSave() {
20 Users users = new Users();
21 users.setAddress("北京市海淀");
22 users.setAge(20);
23 users.setName("张三");
24 this.usersDao.save(users);
25 }
26
27 }
1 . ____ _ __ _ _
2 /\\ / ___‘_ __ _ _(_)_ __ __ _ \ \ \ \
3 ( ( )\___ | ‘_ | ‘_| | ‘_ \/ _` | \ \ \ \
4 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
5 ‘ |____| .__|_| |_|_| |_\__, | / / / /
6 =========|_|==============|___/=/_/_/_/
7 :: Spring Boot :: (v2.2.6.RELEASE)
8
9 2020-05-20 13:40:41.734 INFO 14492 --- [ main] c.b.s.SpringbootJpaApplicationTests : Starting SpringbootJpaApplicationTests on DESKTOP-V37QSSE with PID 14492 (started by biehl in D:\program\idea\IntelliJ IDEA 2019.1.3\workspace_idea\springboot-jpa)
10 2020-05-20 13:40:41.736 INFO 14492 --- [ main] c.b.s.SpringbootJpaApplicationTests : No active profile set, falling back to default profiles: default
11 2020-05-20 13:40:43.891 INFO 14492 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
12 2020-05-20 13:40:44.000 INFO 14492 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 96ms. Found 1 JPA repository interfaces.
13 2020-05-20 13:40:45.245 INFO 14492 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
14 2020-05-20 13:40:45.451 INFO 14492 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
15 2020-05-20 13:40:45.813 INFO 14492 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
16 Loading class `com.mysql.jdbc.Driver‘. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver‘. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
17 2020-05-20 13:40:47.129 INFO 14492 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
18 2020-05-20 13:40:47.326 ERROR 14492 --- [reate-173197870] com.alibaba.druid.pool.DruidDataSource : create connection SQLException, url: jdbc:mysql://127.0.0.1:3306/biehl?useUnicode=true&characterEncoding=utf8, errorCode 0, state 01S00
19
20 java.sql.SQLException: The server time zone value ‘?й???????‘ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the ‘serverTimezone‘ configuration property) to use a more specifc time zone value if you want to utilize time zone support.
21 at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.19.jar:8.0.19]
22 at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19]
23 at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.19.jar:8.0.19]
24 at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.19.jar:8.0.19]
25 at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) ~[mysql-connector-java-8.0.19.jar:8.0.19]
26 at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76) ~[mysql-connector-java-8.0.19.jar:8.0.19]
27 at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.19.jar:8.0.19]
28 at com.mysql.cj.jdbc.ConnectionImpl.
1 package com.bie.springboot.dao;
2
3 import com.bie.springboot.po.Users;
4 import org.springframework.data.repository.Repository;
5
6 import java.util.List;
7
8 /**
9 * Repository接口的方法名称命名查询。
10 */
11 public interface UsersRepositoryByName extends Repository
1 package com.bie.springboot;
2
3 import com.bie.springboot.dao.UsersDao;
4 import com.bie.springboot.dao.UsersRepositoryByName;
5 import com.bie.springboot.po.Users;
6 import org.junit.jupiter.api.Test;
7 import org.junit.runner.RunWith;
8 import org.springframework.beans.factory.annotation.Autowired;
9 import org.springframework.boot.test.context.SpringBootTest;
10 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
11
12 import java.util.List;
13
14 @RunWith(SpringJUnit4ClassRunner.class)
15 @SpringBootTest(classes = SpringbootJpaApplication.class)
16 // 启动器,将测试类和启动器整合在一起
17 class SpringbootJpaApplicationTests {
18
19 @Autowired
20 private UsersRepositoryByName usersRepositoryByName;
21
22
23 @Test
24 public void testFindByName() {
25 List
1 package com.bie.springboot.dao;
2
3 import com.bie.springboot.po.Users;
4 import org.springframework.data.jpa.repository.Modifying;
5 import org.springframework.data.jpa.repository.Query;
6 import org.springframework.data.repository.Repository;
7
8 import javax.transaction.Transactional;
9 import java.util.List;
10
11 /**
12 * Repository接口,提供了基于@Query注解的查询与更新方式。
13 */
14 public interface UsersRepositoryQueryAnnotation extends Repository
1 package com.bie.springboot;
2
3 import com.bie.springboot.dao.UsersRepositoryQueryAnnotation;
4 import com.bie.springboot.po.Users;
5 import org.junit.jupiter.api.Test;
6 import org.junit.runner.RunWith;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.boot.test.context.SpringBootTest;
9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10
11 import java.util.List;
12
13 @RunWith(SpringJUnit4ClassRunner.class)
14 @SpringBootTest(classes = SpringbootJpaApplication.class)
15 // 启动器,将测试类和启动器整合在一起
16 class SpringbootJpaApplicationTests {
17
18 @Autowired
19 private UsersRepositoryQueryAnnotation usersRepositoryQueryAnnotation;
20
21 @Test
22 public void testFindByNameUsrHQL() {
23 List
1 . ____ _ __ _ _
2 /\\ / ___‘_ __ _ _(_)_ __ __ _ \ \ \ \
3 ( ( )\___ | ‘_ | ‘_| | ‘_ \/ _` | \ \ \ \
4 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
5 ‘ |____| .__|_| |_|_| |_\__, | / / / /
6 =========|_|==============|___/=/_/_/_/
7 :: Spring Boot :: (v2.2.6.RELEASE)
8
9 2020-05-20 15:40:24.270 INFO 3352 --- [ main] c.b.s.SpringbootJpaApplicationTests : Starting SpringbootJpaApplicationTests on DESKTOP-V37QSSE with PID 3352 (started by biehl in D:\program\idea\IntelliJ IDEA 2019.1.3\workspace_idea\springboot-jpa)
10 2020-05-20 15:40:24.273 INFO 3352 --- [ main] c.b.s.SpringbootJpaApplicationTests : No active profile set, falling back to default profiles: default
11 2020-05-20 15:40:25.690 INFO 3352 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
12 2020-05-20 15:40:25.786 INFO 3352 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 77ms. Found 3 JPA repository interfaces.
13 2020-05-20 15:40:26.477 INFO 3352 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
14 2020-05-20 15:40:26.569 INFO 3352 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
15 2020-05-20 15:40:26.776 INFO 3352 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
16 Loading class `com.mysql.jdbc.Driver‘. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver‘. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
17 2020-05-20 15:40:27.736 INFO 3352 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
18 2020-05-20 15:40:27.895 INFO 3352 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
19 2020-05-20 15:40:28.764 INFO 3352 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
20 2020-05-20 15:40:28.771 INFO 3352 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit ‘default‘
21 2020-05-20 15:40:29.064 WARN 3352 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
22 2020-05-20 15:40:29.492 WARN 3352 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘requestMappingHandlerAdapter‘ defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed through method ‘requestMappingHandlerAdapter‘ parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘mvcConversionService‘ defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method ‘mvcConversionService‘ threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘usersRepositoryQueryAnnotation‘: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: JDBC style parameters (?) are not supported for JPA queries.
23 Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘requestMappingHandlerAdapter‘ defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed through method ‘requestMappingHandlerAdapter‘ parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘mvcConversionService‘ defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method ‘mvcConversionService‘ threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘usersRepositoryQueryAnnotation‘: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: JDBC style parameters (?) are not supported for JPA queries.
24 2020-05-20 15:40:29.492 INFO 3352 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit ‘default‘
25 2020-05-20 15:40:29.506 INFO
上一篇:SpringBoot(2.1.9.RELEASE)集成MyBatis
下一篇:Spring 依赖注入(DI)详解 [Spring][依赖注入的 6 种实现方式][setter注入][构造器注入][注解注入][自动装配注入][静态工厂注入][实例工厂注入]
文章标题:Spring Boot整合Spring Data JPA
文章链接:http://soscw.com/index.php/essay/42667.html