springboot整合hibernate
看完了上一篇文章,相信对hibernate有了点了解,再看看springboot整合hibernate
1使用springinit选择jpa和mysqldriv和web快速搭建
2创建普通maven在pom.xml文件里面添加要使用的jpa依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
下面再看看完整版的依赖
<dependencies> <!-- 添加对jsp视图解析的支持 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!-- 只需引入spring-boot-devtools 即可实现热部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!-- Json包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.16</version> </dependency> <!-- 为了监控数据库 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.25</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency> <!-- Junit 单元测试 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.0</version> </dependency>
添加依赖之后需要配置一些连接mysql所需要的配置,创建一个application.properties:
resources下的应用配置文件application.properties。在myecplise里面创建配置文件是放在src文件夹下面,
但是最后编译出来的文件还是在classes文件夹下面
先来个最简单的
spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root
再看个加强版本
# 数据库访问配置 # 主数据源,默认的 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username= root spring.datasource.password= root spring.datasource.driverClassName = com.mysql.jdbc.Driver # 下面为连接池的补充设置,应用到上面所有数据源中 # 初始化大小,最小,最大 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 # 配置获取连接等待超时的时间 spring.datasource.maxWait=60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 spring.datasource.timeBetweenEvictionRunsMillis=60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false # 打开PSCache,并且指定每个连接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 spring.datasource.filters=stat,wall,log4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 合并多个DruidDataSource的监控数据 spring.datasource.useGlobalDataSourceStat=true #JPA Configuration: spring.jpa.database=MYSQL # Show or not log for each sql query spring.jpa.show-sql=false spring.jpa.generate-ddl=true # Hibernate ddl auto (create, create-drop, update) spring.jpa.hibernate.ddl-auto=create #spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy #spring.jpa.database=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.mvc.view.prefix=/WEB-INF/view/ spring.mvc.view.suffix=.jsp #spring.resources.static-locations=classpath:/resources/,classpath:/static/
若需要部署到外部的tomcat容器中,则添加下面类即可。
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; /** * 修改启动类,继承 SpringBootServletInitializer 并重写 configure 方法 * @author ZSX * */ public class SpringBootStartApplication extends SpringBootServletInitializer { private static final Logger logger = LoggerFactory.getLogger(SpringBootStartApplication.class); @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(Application.class); } }
然后创建实体类
这里创建一个简单的User实体类,需要用到javax中的Entity,Id,GeneratedValue与GenerationType注解.
Entity用于标识实体类,Id用于标识主键,GeneratedValue与GenerationType用于配置主键.
@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; 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; } }
创建仓库UserRepository保存用户记录.需要继承CrudRepository<T,ID>,第一个类型为实体类,第二个类型为主键类型.
import org.springframework.data.repository.CrudRepository; public interface UserRepository extends CrudRepository<User,Integer> { }
其余交给hibernate
如控制层的controller就这样
@Controller @RequestMapping(path = "/demo") public class MainController { @Autowired private UserRepository userRepository; @PostMapping(path = "/add") public @ResponseBody String addNewUser(@RequestParam String name) { User user = new User(); user.setName(name); userRepository.save(user); return "Saved."; } @GetMapping(path = "/all") public @ResponseBody Iterable<User> getAllUsers() { return userRepository.findAll(); } }