五、spring boot 集成 jpa+hibernate+jdbcTemplate

1.pom添加依赖

       <!-- spring data jpa,会注入tomcat jdbc pool/hibernate等 -->     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.42</version>
        </dependency>

2.添加数据源配置(DataSource啥的,一系列对象spring boot 都会给你注入的,配置配置即可!)

spring.datasource.url=jdbc:mysql://localhost/test?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#database  pool config
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.tomcat.max-wait=10000
# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=300
# Validate the connection before borrowing it from the pool.
spring.datasource.tomcat.test-on-borrow=true
# initial pool size
spring.datasource.tomcat.initial-size=20
#=====================jpa config================================#实体类维护数据库表结构的具体行为:update/create/create-drop/validate/nonespring.jpa.hibernate.ddl-auto=none#打印sql语句spring.jpa.show-sql=true#格式化输出的json字符串spring.jackson.serialization.indent_output=true

3.新建实体

@Entity
@Table(name="user")
public class User {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name="number")
    private String number;

    @Column(name="name")
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

4.dao层

public interface UserDao{

    User getById(int id);

    User getByNumber(String number);

    int addUser(User user);

    void deleteUserById(int id);

    User updateUser(User user);

}
@Repository
public class UserDaoImpl implements UserDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public User getById(int id) {
        //find by primary key
        return this.entityManager.find(User.class,id);
    }

    @Override
    public User getByNumber(String number) {
        Query query = this.entityManager.createQuery("from User u where u.number=:number",User.class);
        query.setParameter("number",number);
        User user = (User)query.getSingleResult();
        return user;
    }

    @Override
    public int addUser(User user) {
        this.entityManager.persist(user);
        //print the id
        System.out.println(user.getId());
        return user.getId();
    }

    @Override
    public void deleteUserById(int id) {
        User user = this.entityManager.find(User.class,id); //关联到记录,方可删除
        this.entityManager.remove(user);
    }

    @Override
    public User updateUser(User user) {
        User userNew = this.entityManager.merge(user);
        return userNew;
    }
}

5.service层

public interface UserService {

    User getById(int id);

    User getByNumber(String number);

    int addUser(User user,boolean throwEx);

    void deleteUserById(int id);

    User updateUser(User user);
}
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional(readOnly = true)
    public User getById(int id) {
        return userDao.getById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public User getByNumber(String number) {
        return userDao.getByNumber(number);
    }

    @Override
    public int addUser(User user,boolean throwEx) {
        int id= this.userDao.addUser(user);
        if(throwEx){
            throw new RuntimeException("throw a ex");
        }
        return id;
    }

    @Override
    public void deleteUserById(int id) {
        this.userDao.deleteUserById(id);
    }

    @Override
    public User updateUser(User user) {
        return this.userDao.updateUser(user);
    }

}

6.controller层

@Controller("user1")
@RequestMapping("/jpa/user")
public class UserController {
    /**
     * 日志(slf4j->logback)
     */
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 返回text格式数据
     * @param id 主键id
     * @return 用户json字符串
     */
    @RequestMapping("/get/id/{id}")
    @ResponseBody
    public String getUserById(@PathVariable("id")String id){
        logger.info("request /user/get/id/{id}, parameter is "+id);
        User user = userService.getById(Integer.parseInt(id));
        return JSONObject.toJSONString(user);
    }

    /**
     * 返回json格式数据
     * @param number 编号
     * @return 用户
     */
    @RequestMapping("/get/number/{number}")
    @ResponseBody
    public User getUserByNumber(@PathVariable("number")String number){
        User user = userService.getByNumber(number);
        return user;
    }

    @RequestMapping("/add/{number}/{name}")
    @ResponseBody
    public String addUser(@PathVariable("number")String number,@PathVariable("name")String name,boolean throwEx){
        User user = new User();
        user.setNumber(number);
        user.setName(name);
        int id = -1;
        try{
            id = userService.addUser(user,throwEx);
        }catch (RuntimeException ex){
            System.out.println(ex.getMessage());
        }
        return String.valueOf(id);
    }

    @RequestMapping("/delete/{id}")
    @ResponseBody
    public void getUserById(@PathVariable("id")int id){
        this.userService.deleteUserById(id);
    }

    @RequestMapping("/update/{id}/{number}/{name}")
    @ResponseBody
    public User addUser(@PathVariable("id")int id, @PathVariable("number")String number, @PathVariable("name")String name){
        User user = new User();
        user.setId(id);
        user.setNumber(number);
        user.setName(name);
        return userService.updateUser(user);
    }
}

7. spring data jpa新使用方式,更高级

1.dao

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
    /**
     * spring data jpa 会自动注入实现(根据方法命名规范)
     * @return
     */
    User findByNumber(String number);

    @Modifying
    @Query("delete from User u where u.id = :id")
    void deleteUser(@Param("id")int id);
}

2.service

public interface UserService {

    User findById(int id);

    User findByNumber(String number);

    List<User> findAllUserByPage(int page,int size);

    User updateUser(User user,boolean throwEx);

    void deleteUser(int id);
}

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User findById(int id) {
        return this.userRepository.findOne(id);
    }

    @Override
    public User findByNumber(String number) {
        return this.userRepository.findByNumber(number);
    }

    @Override
    public List<User> findAllUserByPage(int page,int size) {
        Pageable pageable = new PageRequest(page, size);
        Page<User> users =  this.userRepository.findAll(pageable);
        return users.getContent();
    }

    @Override
    public User updateUser(User user,boolean throwEx) {
        User userNew = this.userRepository.save(user);
        if(throwEx){
            throw new RuntimeException("throw a ex");
        }
        return userNew;
    }

    @Override
    public void deleteUser(int id) {
        this.userRepository.deleteUser(id);
    }
}

3.controller

@Controller("user2")
@RequestMapping("/datajpa/user")
public class UserController {
    /**
     * 日志(slf4j->logback)
     */
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 返回text格式数据
     * @param id 主键id
     * @return 用户json字符串
     */
    @RequestMapping("/get/id/{id}")
    @ResponseBody
    public String getUserById(@PathVariable("id")String id){
        logger.info("request /user/get/id/{id}, parameter is "+id);
        User user = userService.findById(Integer.parseInt(id));
        return JSONObject.toJSONString(user);
    }

    /**
     * 返回json格式数据
     * @param number 编号
     * @return 用户
     */
    @RequestMapping("/get/number/{number}")
    @ResponseBody
    public User getUserByNumber(@PathVariable("number")String number){
        User user = userService.findByNumber(number);
        return user;
    }

    @RequestMapping("/get/all/{page}/{size}")
    @ResponseBody
    public List<User> getAllUserByPage(@PathVariable("page")int page,@PathVariable("size")int size){
        return this.userService.findAllUserByPage(page,size);
    }

    @RequestMapping("/update/{id}/{number}/{name}")
    @ResponseBody
    public User addUser(@PathVariable("id")int id, @PathVariable("number")String number, @PathVariable("name")String name,boolean throwEx){
        User user = new User();
        user.setId(id);
        user.setNumber(number);
        user.setName(name);
        User userNew = null;
        try{
            userService.updateUser(user,throwEx);
        }catch (RuntimeException ex){
            System.out.println(ex.getMessage());
        }
        return userNew;
    }

    @RequestMapping("/delete/{id}")
    @ResponseBody
    public void getUserById(@PathVariable("id")int id){
        this.userService.deleteUser(id);
    }

}

8.注入jdbcTemplate和transactionTemplate,使用传统方式操作数据库,更加灵活,方法如下

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 手动控制事物测试
     * @param throwEx
     */
    @Override
    public void testTransactionManually(boolean throwEx) {

        try {
            transactionTemplate.execute(new TransactionCallback<Boolean>() {

                /**
                 * 事物代码
                 *
                 * @param transactionStatus 事物状态
                 * @return 是否成功
                 */
                @Override
                public Boolean doInTransaction(TransactionStatus transactionStatus) {
                    User user = new User();
                    user.setId(1);
                    int a = new Random().nextInt(10); //0-9
                    user.setNumber("10000u" + a);
                    jdbcTemplate.update("UPDATE USER SET NUMBER=? WHERE ID=?", new Object[]{user.getNumber(), user.getId()}, new int[]{Types.VARCHAR, Types.INTEGER});
                    if (throwEx) {
                        throw new RuntimeException("try throw exception"); //看看会不会回滚
                    }
                    return true;
                }
            });
        }catch (RuntimeException ex){
            System.out.println(ex.getMessage());
        }

    }

    /**
     * 手动执行jdbc测试
     */
    @Override
    public void testJdbcTemplate() {
        User  user = new User();
        int a = new Random().nextInt(10); //0-9
        user.setNumber("10000i"+ a );
        user.setName("name"+a);
        this.jdbcTemplate.update("INSERT into USER(NUMBER,NAME )VALUES (?,?)",user.getNumber(),user.getName());
    }

至此,我已经讲了三种方式(jpa两种+jdbcTemplate)如何操作数据库了,你爱怎么用就怎么用,上述代码均是实践证明可行的!

时间: 2025-01-02 17:21:56

五、spring boot 集成 jpa+hibernate+jdbcTemplate的相关文章

Spring boot之 JPA/Hibernate/Spring Data

1.什么是JPA? JPA全称Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中. JPA(Java Persistence API)是Sun官方提出的Java持久化规范.它为Java开发人员提供了一种对象/关系映射工具来管理Java应用中的关系数据. 持久化 持久化(Persistence),即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘).持久化的主要应用是将内存中的对象存储在的数据库

spring boot(十五)spring boot+thymeleaf+jpa增删改查示例

快速上手 配置文件 pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.

spring boot 集成 Mybatis,JPA

相对应MyBatis, JPA可能大家会比较陌生,它并不是一个框架,而是一组规范,其使用跟Hibernate 差不多,原理层面的东西就不多讲了,主要的是应用. Mybatis就不多说了,SSM这三个框架现在基本上都是基本框架了. MyBatis 与 Spring boot 整合时除了添加必要的jar, 插件.在applicatoin.properties/application.yml 中添加相应的配置. 注意的一点就是在启动类中记得添加@MapperScan("com.spSystem.map

170711、spring boot 集成shiro

这篇文章我们来学习如何使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉及到这方面的需求.在Java领域一般有Spring Security.Apache Shiro等安全框架,但是由于Spring Security过于庞大和复杂,大多数公司会选择Apache Shiro来使用,这篇文章会先介绍一下Apache Shiro,在结合Spring Boot给出使用案例. Apache Shiro What is Apache Shiro?

Spring Boot 集成 MyBatis(四)

Spring Boot 集成 MyBatis A.ORM框架是什么? 对象关系映射(Object Relational Mapping,简称 ORM)模式是一种为了解决面向对象与关系数据库存在的 互不匹配的现象技术.简单的说,ORM 是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自 动持久化到关系数据库中. B.为什么需要ORM框架 当开发一个应用程序的时候(不使用 O/R Mapping),可能会写不少数据访问层的代码,用来从数据库保存. 删除.读取对象信息等.在 DAL 中写了很

Spring Boot集成Spring Scheduler和Quartz Scheduler

本文介绍了Spring Boot集成Spring Scheduler和Quartz Scheduler的基础知识,利用ShedLock解决Spring Scheduler多实例运行冲突,介绍了Quartz ScheduleBuilder.Calendar,介绍了动态创建Quartz Job的方法. GitHub源码 Spring Scheduler Spring Framework提供了简单.易用的Job调度框架Spring Scheduler. 示例 在Spring Boot中,只需两步即可启

Spring Boot 整合 JPA 使用多个数据源

介绍# JPA(Java Persistence API)Java 持久化 API,是 Java 持久化的标准规范,Hibernate 是持久化规范的技术实现,而 Spring Data JPA 是在 Hibernate 基础上封装的一款框架.第一次使用 Spring JPA 的时候,感觉这东西简直就是神器,几乎不需要写什么关于数据库访问的代码一个基本的 CURD 的功能就出来了.在这篇文章中,我们将介绍 Spring Boot 整合 JPA 使用多个数据源的方法.开发环境: Spring Bo

Spring + SpringMVC + Druid + JPA(Hibernate impl) 给你一个稳妥的后端解决方案

最近手头的工作不太繁重,自己试着倒腾了一套用开源框架组建的 JavaWeb 后端解决方案. 感觉还不错的样子,但实践和项目实战还是有很大的落差,这里只做抛砖引玉之用. 项目 git 地址:https://git.oschina.net/LanboEx/sdh.git 大体采用的开源项目有:Spring + SpringMVC + Druid + JPA(Hibernate Impl). 1. 采用到的开源项目漫谈 Spring 迷人的依赖注入特性, 使其已经稳稳的占据在 JavaEE 项目引用开

Spring Boot集成Jasypt安全框架

Jasypt安全框架提供了Spring的集成,主要是实现 PlaceholderConfigurerSupport类或者其子类. 在Sring 3.1之后,则推荐使用PropertySourcesPlaceholderConfigurer类作为属性替换配置类,这里Spring集成Jasypt则使用Jasypt对属性替换配置类的实现.EncryptablePropertySourcesPlaceholderConfigurer. 在Spring中集成比较容易,而且Jasypt官方也给出了配置Bea