Spring Boot整合spring-data-jpa案例

第一、SpringData JPA是什么?
SpringData JPA只是SpringData中的一个子模块,JPA是一套标准接口,而Hibernate是JPA的实现,SpringData JPA 底层默认实现是使用Hibernate。

第二、编码
1.新建Maven工程,在pom.xml中增加SpringData JPA的依赖。

		
			org.springframework.boot
			spring-boot-starter-data-jpa
		

pom.xml的基本配置可参考:Spring Boot 2 入门案例
2.com.shi.dto.User.java

package com.shi.dto;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 * 实体类
 * @author shixiangcheng
 * 2019-09-08
 */
@Entity //表名当前类是实体类
@Table(name="t_user")  //映射的表
public class User implements Serializable{
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="id")//对应列
	@GeneratedValue(strategy=GenerationType.IDENTITY)//自增长
	private Integer id;
	@Column(name="name")//对应列
	private String name;
	@Column(name="pwd")//对应列
	private String pwd;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
}

2.com.shi.web.controller.UserController.java

package com.shi.web.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.shi.dto.User;
import com.shi.service.UserService;
/**
 * 示例
 * @author shixiangcheng
 * 2019-09-07
 */
@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	@RequestMapping("/queryList")
	public List queryList(){
		return this.userService.queryList();
	}
}

3.com.shi.service.UserService.java

package com.shi.service;
import java.util.List;
import com.shi.dto.User;
/**
 * service接口
 * @author shixiangcheng
 * 2019-09-08
 */
public interface UserService{
	/**
	 * 查询列表
	 * @return
	 */
	public List queryList();
}

4.com.shi.service.impl.UserServiceImpl.java

package com.shi.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shi.dao.UserDAO;
import com.shi.dto.User;
import com.shi.service.UserService;
/**
 * service接口实现类
 * @author shixiangcheng
 * 2019-09-08
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDAO userDAO;
	@Override
	public List queryList() {
		return this.userDAO.findAll();
	}
}

5.com.shi.dao.UserDAO.java

package com.shi.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.shi.dto.User;
/**
 * DAO接口
 * @author shixiangcheng
 * 2019-09-08
 */
@Repository("userDAO")
//JpaRepository T:实体类;ID:主键类型
public interface UserDAO extends JpaRepository{
}

6.resources目录下:application.properties

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/memberdb
spring.datasource.username=root
spring.datasource.password=1234

spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy

7.com.shi.RunApplication.java

package com.shi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * SpringBoot 启动类(引导类)
 * @author shixiangcheng
 * 2019-09-07
 */
@SpringBootApplication//表面当前类是SpringBoot的引导类
public class RunApplication {
	public static void main(String[] args) {
		System.out.println("start spring boot");
		SpringApplication.run(RunApplication.class, args);
	}
}

8.运行引导类,浏览器测试
Spring Boot整合spring-data-jpa案例_第1张图片
控制台日志

start spring boot

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-09-08 11:20:30.960  INFO 5980 --- [           main] com.shi.RunApplication                   : Starting RunApplication on AndyShi-PC with PID 5980 (D:\maven\workspace\SpringBoot\target\classes started by Andy.Shi in D:\maven\workspace\SpringBoot)
2019-09-08 11:20:30.970  INFO 5980 --- [           main] com.shi.RunApplication                   : No active profile set, falling back to default profiles: default
2019-09-08 11:20:32.680  INFO 5980 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-09-08 11:20:32.875  INFO 5980 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 158ms. Found 1 repository interfaces.
2019-09-08 11:20:33.877  INFO 5980 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$9d566ae] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-08 11:20:35.197  INFO 5980 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-09-08 11:20:35.280  INFO 5980 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-09-08 11:20:35.281  INFO 5980 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-09-08 11:20:35.749  INFO 5980 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-09-08 11:20:35.750  INFO 5980 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4646 ms
2019-09-08 11:20:36.312  INFO 5980 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
	name: default
	...]
2019-09-08 11:20:36.462  INFO 5980 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.10.Final}
2019-09-08 11:20:36.465  INFO 5980 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-09-08 11:20:36.795  INFO 5980 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-09-08 11:20:37.191  INFO 5980 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-09-08 11:20:38.069  INFO 5980 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-09-08 11:20:38.100  INFO 5980 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-09-08 11:20:40.589  INFO 5980 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-09-08 11:20:42.218  INFO 5980 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-08 11:20:42.316  WARN 5980 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : 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
2019-09-08 11:20:42.912  INFO 5980 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-09-08 11:20:42.915  INFO 5980 --- [           main] com.shi.RunApplication                   : Started RunApplication in 13.287 seconds (JVM running for 14.05)
2019-09-08 11:20:48.788  INFO 5980 --- [nio-8080-exec-3] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-09-08 11:20:48.789  INFO 5980 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-09-08 11:20:48.804  INFO 5980 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed initialization in 15 ms
2019-09-08 11:20:49.015  INFO 5980 --- [nio-8080-exec-3] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_0_, user0_.name as name2_0_, user0_.pwd as pwd3_0_ from t_user user0_

欢迎大家积极留言交流学习心得。谢谢!

你可能感兴趣的:(Spring,Boot)