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

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è)務(wù)邏輯
*/
@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 進(jìn)行修飾. 以通知 SpringData, 這是一個 UPDATE 或 DELETE 操作
(3)UPDATE 或 DELETE 操作需要使用事務(wù),此時需要定義 Service 層,在 Service 層的方法上添加事務(wù)操作;
(4)默認(rèn)情況下, SpringData 的每個方法上有事務(wù), 但都是一個只讀事務(wù)。
@Transactional:
A. 一個功能是否要事務(wù),必須納入設(shè)計(jì)、編碼考慮。不能僅僅完成了基本功能就ok。
B. 如果加了事務(wù),必須做好開發(fā)環(huán)境測試(測試環(huán)境也盡量觸發(fā)異常、測試回滾),確保事務(wù)生效。
C. 以下列了事務(wù)使用過程的注意事項(xiàng),請大家留意。
1. 不要在接口上聲明@Transactional ,而要在具體類的方法上使用 @Transactional 注解,否則注解可能無效。
2.不要圖省事,將@Transactional放置在類級的聲明中,放在類聲明,會使得所有方法都有事務(wù)。故@Transactional應(yīng)該放在方法級別,不需要使用事務(wù)的方法,就不要放置事務(wù),比如查詢方法。否則對性能是有影響的。
3.使用了@Transactional的方法,對同一個類里面的方法調(diào)用,
@Transactional無效。比如有一個類Test,它的一個方法A,A再調(diào)用Test本類的方法B(不管B是否public還是private),但A沒有聲明注解事務(wù),而B有。則外部調(diào)用A之后,B的事務(wù)是不會起作用的。(經(jīng)常在這里出錯)
4.使用了@Transactional的方法,只能是public,@Transactional注解的方法都是被外部其他類調(diào)用才有效,故只能是public。道理和上面的有關(guān)聯(lián)。故在
protected、private 或者 package-visible 的方法上使用 @Transactional
注解,它也不會報(bào)錯,但事務(wù)無效。
5.經(jīng)過在ICORE-CLAIM中測試,效果如下:
A.拋出受查異常XXXException,事務(wù)會回滾。
B.拋出運(yùn)行時異常NullPointerException,事務(wù)會回滾。
C.Quartz中,execute直接調(diào)用加了@Transactional方法,可以回滾;間接調(diào)用,不會回滾。(即上文3點(diǎn)提到的)
D.異步任務(wù)中,execute直接調(diào)用加了@Transactional方法,可以回滾;間接調(diào)用,不會回滾。(即上文3點(diǎn)提到的)
E.在action中加上@Transactional,不會回滾。切記不要在action中加上事務(wù)。
F.在service中加上@Transactional,如果是action直接調(diào)該方法,會回滾,如果是間接調(diào),不會回滾。(即上文3提到的)
G.在service中的private加上@Transactional,事務(wù)不會回滾。
application:
package com.song.configuration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
*
* 項(xiàng)目啟動入口,配置包根路徑
*/
@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實(shí)現(xiàn)簡單的增刪改查示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Spring Data Jpa的CriteriaQuery一個陷阱
使用Spring Data Jpa的CriteriaQuery進(jìn)行動態(tài)條件查詢時,可能會遇到一個陷阱,當(dāng)條件為空時,查詢不到任何結(jié)果,并不是期望的返回所有結(jié)果。這是為什么呢?2020-11-11
確保SpringBoot定時任務(wù)只執(zhí)行一次的常見方法小結(jié)
在Spring Boot項(xiàng)目中,確保定時任務(wù)只執(zhí)行一次是一個常見的需求,這種需求可以通過多種方式來實(shí)現(xiàn),以下是一些常見的方法,它們各具特點(diǎn),可以根據(jù)項(xiàng)目的實(shí)際需求來選擇最合適的方法,需要的朋友可以參考下2024-10-10
源碼解析Spring 數(shù)據(jù)庫異常抽理知識點(diǎn)總結(jié)
在本篇文章里小編給大家分享了關(guān)于源碼解析Spring 數(shù)據(jù)庫異常抽理知識點(diǎn)內(nèi)容,對此有需要的朋友們學(xué)習(xí)參考下。2019-05-05
Java 實(shí)現(xiàn)線程池任務(wù)編排的示例代碼
任務(wù)編排是將多個任務(wù)按照特定的依賴關(guān)系和執(zhí)行順序進(jìn)行組織和管理的過程,以確保任務(wù)能按預(yù)定邏輯順序高效執(zhí)行,本文就來介紹一下Java 實(shí)現(xiàn)線程池任務(wù)編排的示例代碼,感興趣的可以了解一下2024-10-10
Java 實(shí)現(xiàn)簡單Socket 通信的示例
這篇文章主要介紹了Java 實(shí)現(xiàn)簡單Socket 通信的示例,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下2021-03-03
Java?HashSet的Removals()方法注意事項(xiàng)
這篇文章主要介紹了Java?HashSet的Removals()方法注意事項(xiàng),文章圍繞制主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-06-06

