溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Springboot+hibernate實現(xiàn)簡單的增刪改查示例

發(fā)布時間:2020-10-14 00:00:02 來源:腳本之家 閱讀:457 作者:*眉間緣* 欄目:編程語言

1、創(chuàng)建好項目之后在Springboot+hibernate實現(xiàn)簡單的增刪改查示例配置端口號(也可以不用配置,默認端口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>

整個包結(jié)構(gòu)

Springboot+hibernate實現(xiàn)簡單的增刪改查示例

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業(yè)務邏輯
 */
@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>{
  /*
  * 根據(jù)用戶名查詢
  * */
  @Query("select t from User t where t.name = :name")
  User findByUserName(@Param("name") String name);

  /*
  * 查詢?nèi)?  * */
  @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. 如果加了事務,必須做好開發(fā)環(huán)境測試(測試環(huán)境也盡量觸發(fā)異常、測試回滾),確保事務生效。

C. 以下列了事務使用過程的注意事項,請大家留意。

1. 不要在接口上聲明@Transactional ,而要在具體類的方法上使用 @Transactional 注解,否則注解可能無效。

2.不要圖省事,將@Transactional放置在類級的聲明中,放在類聲明,會使得所有方法都有事務。故@Transactional應該放在方法級別,不需要使用事務的方法,就不要放置事務,比如查詢方法。否則對性能是有影響的。

3.使用了@Transactional的方法,對同一個類里面的方法調(diào)用,

@Transactional無效。比如有一個類Test,它的一個方法A,A再調(diào)用Test本類的方法B(不管B是否public還是private),但A沒有聲明注解事務,而B有。則外部調(diào)用A之后,B的事務是不會起作用的。(經(jīng)常在這里出錯)

4.使用了@Transactional的方法,只能是public,@Transactional注解的方法都是被外部其他類調(diào)用才有效,故只能是public。道理和上面的有關聯(lián)。故在

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

注解,它也不會報錯,但事務無效。

5.經(jīng)過在ICORE-CLAIM中測試,效果如下:

A.拋出受查異常XXXException,事務會回滾。

B.拋出運行時異常NullPointerException,事務會回滾。

C.Quartz中,execute直接調(diào)用加了@Transactional方法,可以回滾;間接調(diào)用,不會回滾。(即上文3點提到的)

D.異步任務中,execute直接調(diào)用加了@Transactional方法,可以回滾;間接調(diào)用,不會回滾。(即上文3點提到的)

E.在action中加上@Transactional,不會回滾。切記不要在action中加上事務。

F.在service中加上@Transactional,如果是action直接調(diào)該方法,會回滾,如果是間接調(diào),不會回滾。(即上文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實現(xiàn)簡單的增刪改查示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI