Springboot+hibernate实现简单的增删改查示例

 更新时间:2018年08月19日 10:55:41   作者:*眉间缘*  
今天小编就为大家分享一篇Springboot+hibernate实现简单的增删改查示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1、创建好项目之后在配置端口号(也可以不用配置,默认端口8080)

#server
server.port=8080
server.tomcat.uri-encoding=utf-8

2、配置mysql

#MySQL
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
spring.datasource.username=*****
spring.datasource.password=*****

3、配置jpa以及视图层

#Spring Data JPA
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
# Naming strategy
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

#视图层控制
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/static/**

4、在pom中加入springboot需要的依赖

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

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
      <version>1.4.0.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
<!--    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
      <version>1.4.3.RELEASE</version>
    </dependency>-->
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
      <version>1.5.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.46</version>
    </dependency>


  </dependencies>

整个包结构

Controller

package com.song.configuration.controller;

import com.alibaba.fastjson.JSONObject;
import com.song.configuration.entity.User;
import com.song.configuration.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * 
 * User控制层
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
  @Autowired
  private UserService userService;

  @RequestMapping(value = "/index")
  public String index(){
    return "user/index";
  }

  @RequestMapping(value = "/show",method = RequestMethod.GET)
  @ResponseBody
  public String show(@RequestParam(value = "name")String name){
    User user = userService.findUserByName(name);
    if(null != user)
      return user.getId()+"/"+user.getName()+"/"+user.getPassword();
    else return "null";
  }

  @RequestMapping("/showlist")
  @ResponseBody
  public JSONObject showList(){
    List<User> list = userService.find();
    JSONObject jo = new JSONObject();
    if(list!=null){

      jo.put("code",0);
      jo.put("msg",true);
      jo.put("count",list.size());
      jo.put("data",list);
    }
    return jo;
  }

  @RequestMapping("/delete")
  @ResponseBody
  public String deleteUserById(@RequestParam(value = "id")Integer id){
    return userService.deleteUserById(id);
  }

  @RequestMapping("/update")
  @ResponseBody
  public String queryUserById(@RequestParam(value = "id")Integer id,@RequestParam(value = "name")String name){

    return userService.queryUserById(id,name);
  }

  @RequestMapping("/add")
  @ResponseBody
  public String countUserBy(@RequestParam(value = "id")Integer id,@RequestParam(value = "name")String name,@RequestParam(value = "password")String password){
    return userService.countUserBy(id,name,password);
  }
}

service

package com.song.configuration.service;

import com.song.configuration.entity.User;
import com.song.configuration.repository.UserRepositoty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 
 * User业务逻辑
 */
@Service
public class UserService {
  @Autowired
  private UserRepositoty userRepositoty;

  public User findUserByName(String name) {
    User user = null;
    try {
      user = userRepositoty.findByUserName(name);
    } catch (Exception e) {
    }
    return user;
  }

  public List<User> find() {
    List<User> list = null;
    try {
      list = userRepositoty.find();
    } catch (Exception e) {
    }
    return list;
  }

  public String deleteUserById(Integer id){
    int a = userRepositoty.deleteUserById(id);
    return "chenggong";
  }

  public String queryUserById(Integer id ,String name){
    int a = userRepositoty.queryUserById(id,name);
    return "成功";
  }

  public String countUserBy(Integer id ,String name ,String password){
    int a = userRepositoty.countUserBy(id,name,password);
    return "成功";
  }
}

Repository

package com.song.configuration.repository;

import com.song.configuration.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Song on 2017/2/15.
 * User表操作接口
 */
@Repository
public interface UserRepositoty extends JpaRepository<User,Long>{
  /*
  * 根据用户名查询
  * */
  @Query("select t from User t where t.name = :name")
  User findByUserName(@Param("name") String name);

  /*
  * 查询全部
  * */
  @Query("select t from User t")
  List<User> find();

  /*
  * 删除 必须加入@Modifying和@Transactional
  * */
  @Modifying
  @Transactional
  @Query("delete from User u where u.id=:id")
  public int deleteUserById(@Param("id") Integer id);


  @Modifying
  @Transactional
  @Query("update User u set u.name = :name where u.id=:id")
  public int queryUserById(@Param("id") Integer id,@Param("name") String name);
    
  @Query(value = "insert into User value(?,?,?)", nativeQuery = true)
  @Transactional
  @Modifying
  public int countUserBy(@Param("id")Integer id,@Param("name") String name,@Param("password") String password);
}

@modifying:

(1)可以通过自定义的 JPQL 完成 UPDATE 和 DELETE 操作。注意: JPQL 不支持使用 INSERT;

(2)在 @Query 注解中编写 JPQL 语句, 但必须使用 @Modifying 进行修饰. 以通知   SpringData, 这是一个 UPDATE 或 DELETE 操作

(3)UPDATE 或 DELETE 操作需要使用事务,此时需要定义 Service 层,在 Service 层的方法上添加事务操作;

(4)默认情况下, SpringData 的每个方法上有事务, 但都是一个只读事务。

@Transactional:

A. 一个功能是否要事务,必须纳入设计、编码考虑。不能仅仅完成了基本功能就ok。

B. 如果加了事务,必须做好开发环境测试(测试环境也尽量触发异常、测试回滚),确保事务生效。

C. 以下列了事务使用过程的注意事项,请大家留意。

1. 不要在接口上声明@Transactional ,而要在具体类的方法上使用 @Transactional 注解,否则注解可能无效。

2.不要图省事,将@Transactional放置在类级的声明中,放在类声明,会使得所有方法都有事务。故@Transactional应该放在方法级别,不需要使用事务的方法,就不要放置事务,比如查询方法。否则对性能是有影响的。

3.使用了@Transactional的方法,对同一个类里面的方法调用,

@Transactional无效。比如有一个类Test,它的一个方法A,A再调用Test本类的方法B(不管B是否public还是private),但A没有声明注解事务,而B有。则外部调用A之后,B的事务是不会起作用的。(经常在这里出错)

4.使用了@Transactional的方法,只能是public,@Transactional注解的方法都是被外部其他类调用才有效,故只能是public。道理和上面的有关联。故在

protected、private 或者 package-visible 的方法上使用 @Transactional

注解,它也不会报错,但事务无效。

5.经过在ICORE-CLAIM中测试,效果如下:

A.抛出受查异常XXXException,事务会回滚。

B.抛出运行时异常NullPointerException,事务会回滚。

C.Quartz中,execute直接调用加了@Transactional方法,可以回滚;间接调用,不会回滚。(即上文3点提到的)

D.异步任务中,execute直接调用加了@Transactional方法,可以回滚;间接调用,不会回滚。(即上文3点提到的)

E.在action中加上@Transactional,不会回滚。切记不要在action中加上事务。

F.在service中加上@Transactional,如果是action直接调该方法,会回滚,如果是间接调,不会回滚。(即上文3提到的)

G.在service中的private加上@Transactional,事务不会回滚。

application:

package com.song.configuration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * 
 * 项目启动入口,配置包根路径
 */
@SpringBootApplication
@ComponentScan(basePackages = "com.song.configuration")
public class Entry {
  public static void main(String[] args) throws Exception {
    SpringApplication.run(Entry.class, args);
  }
}

Jpaconfiguration:

package com.song.configuration;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "com.song.configuration.repository")
@EntityScan(basePackages = "com.song.configuration.entity")
public class JpaConfiguration {
  @Bean
  PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
    return new PersistenceExceptionTranslationPostProcessor();
  }
}

其他包要在jpaconfiguration所在包下面,不然找不到路径

以上这篇Springboot+hibernate实现简单的增删改查示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • maven搭建spring项目(图文教程)

    maven搭建spring项目(图文教程)

    下面小编就为大家带来一篇maven搭建spring项目(图文教程)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • 一看就懂 详解JAVA泛型通配符T,E,K,V区别

    一看就懂 详解JAVA泛型通配符T,E,K,V区别

    泛型从字面上理解,是指一个类、接口或方法支持多种类型,使之广泛化、一般化和更加通用。通配符只有在修饰一个变量时会用到,使用它可方便地引用包含了多种类型的泛型;下面我们来深入了解一下吧
    2019-06-06
  • Spring AOP注解实战指南

    Spring AOP注解实战指南

    在现代软件开发中,面向切面编程(AOP)是一种强大的编程范式,本文将介绍如何在Spring框架中通过AspectJ注解以及对应的XML配置来实现AOP,在不改变主业务逻辑的情况下增强应用程序的功能,需要的朋友可以参考下
    2024-06-06
  • SpringBoot日志打印实践过程

    SpringBoot日志打印实践过程

    文章介绍了如何在SpringBoot项目中使用Logback实现日志打印,并通过自定义日志打印工具类和日志分文件打印来提高日志排查和监控的效率
    2024-12-12
  • 详解Spring boot Admin 使用eureka监控服务

    详解Spring boot Admin 使用eureka监控服务

    本篇文章主要介绍了详解Spring boot Admin 使用eureka监控服务,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • SpringBoot整合minio服务的示例代码

    SpringBoot整合minio服务的示例代码

    本文主要介绍了SpringBoot整合minio服务的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • java中@JsonValue和@JsonCreator使用

    java中@JsonValue和@JsonCreator使用

    本文主要介绍了java中@JsonValue和@JsonCreator使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-06-06
  • Java设计模式之桥梁(Bridge)模式

    Java设计模式之桥梁(Bridge)模式

    这篇文章主要介绍了Java设计模式之桥梁(Bridge)模式,文中有非常详细的代码示例,对正在学习Java设计模式的小伙伴们有很好的帮助,需要的朋友可以参考下
    2021-05-05
  • 详解spring security四种实现方式

    详解spring security四种实现方式

    这篇文章主要介绍了详解spring security四种实现方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Java并发编程之对象的组合

    Java并发编程之对象的组合

    这篇文章主要介绍了Java并发编程之对象的组合,文章基于Java的相关资料展开主题内容,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-04-04

最新评论