SpringBoot+Hibernate+Spring Data JPA+Maven入门

整合SpringBoot 和 Hibernate,实现简单的CRUD。


框架版本

  • SpringBoot 2.0.0.RELEASE

  • Hibernate 5.2.14.Final


pom.xml文件

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- JPA, Hibernate, mysql -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- mysql数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

在application.properties文件中配置mysql数据源

spring.thymeleaf.cache=false

#Spring Boot中的乱码和编码问题
spring.http.encoding.force=true

########################################################
### datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/springboot
spring.datasource.username = root
spring.datasource.password = password
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#spring.datasource.max-active=20
#spring.datasource.max-idle=8
#spring.datasource.min-idle=8
#spring.datasource.initial-size=10
########################################################
### Java Persistence Api
########################################################
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect

可配置属性总结:

##########################################
###datasource
##########################################
###spring.datasource.url:mysql地址
###spring.datasource.user:数据库用户名
###spring.datasource.password:数据库密码
###spring.datasource.driverClassName:对应数据库驱动
###spring.datasource.max-active:指定连接池中最大的活跃连接数
###spring.datasource.max-idle:指定连接池最大的空闲连接数量
###spring.datasource.min-idle:指定必须保持连接的最小值(For DBCP and Tomcat connection pools)
###spring.datasource.initial-size:指定启动连接池时,初始建立的连接数量
##########################################
###其他信息总结
##########################################
###spring.dao.exceptiontranslation.enabled  是否开启PersistenceExceptionTranslationPostProcessor,默认为true
###spring.datasource.abandon-when-percentage-full  设定超时被废弃的连接占到多少比例时要被关闭或上报
###spring.datasource.allow-pool-suspension  使用Hikari pool时,是否允许连接池暂停,默认为: false
###spring.datasource.alternate-username-allowed  是否允许替代的用户名
###spring.datasource.auto-commit  指定updates是否自动提交.
###spring.datasource.catalog  指定默认的catalog.
###spring.datasource.commit-on-return  设置当连接被归还时,是否要提交所有还未完成的事务
###spring.datasource.connection-init-sql  指定连接被创建,再被添加到连接池之前执行的sql.
###spring.datasource.connection-init-sqls  使用DBCP connection pool时,指定初始化时要执行的sql
###spring.datasource.connection-properties.[key]  在使用DBCP connection pool时指定要配置的属性
###spring.datasource.connection-test-query  指定校验连接合法性执行的sql语句
###spring.datasource.connection-timeout  指定连接的超时时间,毫秒单位.
###spring.datasource.continue-on-error  在初始化数据库时,遇到错误是否继续,默认false
###spring.datasource.data  指定Data (DML)脚本
###spring.datasource.data-source-class-name  指定数据源的全限定名.
###spring.datasource.data-source-jndi  指定jndi的地址
###spring.datasource.data-source-properties.[key]  使用Hikari connection pool时,指定要设置的属性
###spring.datasource.db-properties  使用Tomcat connection pool,指定要设置的属性
###spring.datasource.default-auto-commit  是否自动提交.
###spring.datasource.default-catalog  指定连接默认的catalog.
###spring.datasource.default-read-only  是否设置默认连接只读.
###spring.datasource.default-transaction-isolation  指定连接的事务的默认隔离级别.
###spring.datasource.driver-class-name  指定driver的类名,默认从jdbc url中自动探测.
###spring.datasource.fair-queue  是否采用FIFO返回连接.
###spring.datasource.health-check-properties.[key]  使用Hikari connection pool时,在心跳检查时传递的属性
###spring.datasource.idle-timeout  指定连接多久没被使用时,被设置为空闲,默认为10ms
###spring.datasource.ignore-exception-on-pre-load  当初始化连接池时,是否忽略异常.
###spring.datasource.init-sql  当连接创建时,执行的sql
###spring.datasource.initial-size  指定启动连接池时,初始建立的连接数量
###spring.datasource.initialization-fail-fast  当创建连接池时,没法创建指定最小连接数量是否抛异常
###spring.datasource.initialize  指定初始化数据源,是否用data.sql来初始化,默认: true
###spring.datasource.isolate-internal-queries  指定内部查询是否要被隔离,默认为false
###spring.datasource.jdbc-interceptors  使用Tomcat connection pool时,指定jdbc拦截器,分号分隔
###spring.datasource.jdbc-url  指定JDBC URL.
###spring.datasource.jmx-enabled  是否开启JMX,默认为: false
###spring.datasource.jndi-name  指定jndi的名称.
###spring.datasource.leak-detection-threshold  使用Hikari connection pool时,多少毫秒检测一次连接泄露.
###spring.datasource.log-abandoned  使用DBCP connection pool,是否追踪废弃statement或连接,默认为: false
###spring.datasource.log-validation-errors  当使用Tomcat connection pool是否打印校验错误.
###spring.datasource.login-timeout  指定连接数据库的超时时间.
###spring.datasource.max-age  指定连接池中连接的最大年龄
###spring.datasource.max-lifetime  指定连接池中连接的最大生存时间,毫秒单位.
###spring.datasource.max-open-prepared-statements  指定最大的打开的prepared statements数量.
###spring.datasource.max-wait  指定连接池等待连接返回的最大等待时间,毫秒单位.
###spring.datasource.maximum-pool-size  指定连接池最大的连接数,包括使用中的和空闲的连接.
###spring.datasource.min-evictable-idle-time-millis  指定一个空闲连接最少空闲多久后可被清除.
###spring.datasource.min-idle  指定必须保持连接的最小值(For DBCP and Tomcat connection pools)
###spring.datasource.minimum-idle  指定连接维护的最小空闲连接数,当使用HikariCP时指定.
###spring.datasource.name  指定数据源名.
###spring.datasource.num-tests-per-eviction-run  指定运行每个idle object evictor线程时的对象数量
###spring.datasource.password  指定数据库密码.
###spring.datasource.platform  指定schema要使用的Platform(schema-${platform}.sql),默认为: all
###spring.datasource.pool-name  指定连接池名字.
###spring.datasource.pool-prepared-statements  指定是否池化statements.
###spring.datasource.propagate-interrupt-state  在等待连接时,如果线程被中断,是否传播中断状态.
###spring.datasource.read-only  当使用Hikari connection pool时,是否标记数据源只读
###spring.datasource.register-mbeans  指定Hikari connection pool是否注册JMX MBeans.
###spring.datasource.remove-abandoned  指定当连接超过废弃超时时间时,是否立刻删除该连接.
###spring.datasource.remove-abandoned-timeout  指定连接应该被废弃的时间.
###spring.datasource.rollback-on-return  在归还连接时,是否回滚等待中的事务.
###spring.datasource.schema  指定Schema (DDL)脚本.
###spring.datasource.separator  指定初始化脚本的语句分隔符,默认: ;
###spring.datasource.sql-script-encoding  指定SQL scripts编码.
###spring.datasource.suspect-timeout  指定打印废弃连接前的超时时间.
###spring.datasource.test-on-borrow  当从连接池借用连接时,是否测试该连接.
###spring.datasource.test-on-connect  创建时,是否测试连接
###spring.datasource.test-on-return  在连接归还到连接池时是否测试该连接.
###spring.datasource.test-while-idle  当连接空闲时,是否执行连接测试.
###spring.datasource.time-between-eviction-runs-millis  指定空闲连接检查、废弃连接清理、空闲连接池大小调整之间的操作时间间隔
###spring.datasource.transaction-isolation  指定事务隔离级别,使用Hikari connection pool时指定
###spring.datasource.url  指定JDBC URL.
###spring.datasource.use-disposable-connection-facade  是否对连接进行包装,防止连接关闭之后被使用.
###spring.datasource.use-equals  比较方法名时是否使用String.equals()替换==.
###spring.datasource.use-lock  是否对连接操作加锁
###spring.datasource.username  指定数据库名.
###spring.datasource.validation-interval  指定多少ms执行一次连接校验.
###spring.datasource.validation-query  指定获取连接时连接校验的sql查询语句.
###spring.datasource.validation-query-timeout  指定连接校验查询的超时时间.
###spring.datasource.validation-timeout  设定连接校验的超时时间,当使用Hikari connection pool时指定
###spring.datasource.validator-class-name  用来测试查询的validator全限定名.
###spring.datasource.xa.data-source-class-name  指定数据源的全限定名.
###spring.datasource.xa.properties  指定传递给XA data source的属性
##########################################
##SPring JPA配置信息
##########################################
###spring.jpa.database  指定目标数据库.
###spring.jps.show-sq  是否显示sql语句
###spring.jpa.hibernate.ddl-auto  指定DDL mode (none, validate, update, create, create-drop). 当使用内嵌数据库时,默认是create-drop,否则为none.
###spring.jpa.hibernate.naming-strategy  指定命名策略.
##########################################
###其他
##########################################
###spring.jpa.database-platform  指定目标数据库的类型.
###spring.jpa.generate-ddl  是否在启动时初始化schema,默认为false
###spring.jpa.hibernate.ddl-auto  指定DDL mode (none, validate, update, create, create-drop). 当使用内嵌数据库时,默认是create-drop,否则为none.
###spring.jpa.hibernate.naming-strategy  指定命名策略.
###spring.jpa.open-in-view  是否注册OpenEntityManagerInViewInterceptor,绑定JPA EntityManager到请求线程中,默认为: true
###spring.jpa.properties  添加额外的属性到JPA provider.
###spring.jpa.show-sql  是否开启sql的log,默认为: false
##########################################

编写程序

(1)编写实体类User

package com.tao.springboot.hibernate.entity;

import lombok.Data;

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

/**
 * 创建一个实体类User。
 * 每一个实体类对应数据库中的一张表。
 * 1、使用@Entity注解进行持久化操作,当JPA检测到被@Entity注解的实体类的时候,
 *    会在数据库中自动创建一张对应的表。
 * 2、通过@Table注解来为数据库中将要创建的表命名。
 */
@Entity
@Table(name = "tb_user")
@Data  //lombok的注解
public class User implements Serializable {

    /**
     * 使用@Id注解来指定哪个字段作为主键。
     * 使用@GeneratedValue注解来指定主键的生成策略,mysql默认的是自增长。
     */
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String userName;
    private String password;
}

(2)编写UserDao接口

package com.tao.springboot.hibernate.dao;

import com.tao.springboot.hibernate.entity.User;
import org.springframework.data.repository.CrudRepository;

public interface UserDao extends CrudRepository<User, Integer> {

}

(3)编写UserService接口

package com.tao.springboot.hibernate.service;

import com.tao.springboot.hibernate.entity.User;

import java.util.List;

public interface UserService {

    void save(User user);

    void delete(Integer id);

    List<User> getAll();
}

(4)编写UserService接口的实现类UserServiceImpl

package com.tao.springboot.hibernate.service.impl;

import com.tao.springboot.hibernate.dao.UserDao;
import com.tao.springboot.hibernate.entity.User;
import com.tao.springboot.hibernate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    /**
     * save,update,delete方法需要绑定事务
     * 使用@Transactional进行事务绑定
     */
    /**
     * 保存数据
     * @param user
     */
    @Transactional
    @Override
    public void save(User user) {
        userDao.save(user);
    }

    /**
     * 删除数据
     * @param id
     */
    @Transactional
    @Override
    public void delete(Integer id) {
        userDao.deleteById(id);
    }

    /**
     * 查询数据
     * @return
     */
    @Override
    public List<User> getAll() {

        Iterable<User> users = userDao.findAll();
        Iterator<User> iter = users.iterator();
        List<User> res = new ArrayList<>();
        while(iter.hasNext()) {
            res.add(iter.next());
        }

        return res;
    }
}

(5)编写UserController

package com.tao.springboot.hibernate.web.controller;

import com.tao.springboot.hibernate.entity.User;
import com.tao.springboot.hibernate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping("/hello")
    @ResponseBody
    public String home() {

        return "Hello World!";
    }

    /**
     * 保存一个用户信息
     * @param model
     * @return
     */
    @RequestMapping("/save")
    public String save(Model model) {

        User user = new User();
        user.setUserName("李四");
        user.setPassword("123456789");
        userService.save(user);
        model.addAttribute("msg", "添加数据成功");
        return "result";
    }

    @RequestMapping("/delete")
    public String delete(Model model) {
        userService.delete(1);
        model.addAttribute("msg", "删除数据成功");
        return "result";
    }

    @GetMapping("/all")
    @ResponseBody
    public List<User> getAll() {
        return userService.getAll();
    }
}

(6)在入口函数中添加@EnableJpaRepositories注解和@EntityScan注解

package com.tao.springboot.hibernate;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories("com.tao.springboot.hibernate.dao") // JPA扫描该包路径下的Repositorie
@EntityScan("com.tao.springboot.hibernate.entity") // 扫描Entity实体类
public class SpringbootHibernateApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootHibernateApplication.class, args);
    }
}

(7)启动程序,测试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值