Springboot+hibernate简单的增删改查
1、创建好项目之后在配置端口号(也可以不用配置,默认端口8080)
#server
server.port=
server.tomcat.uri-encoding=utf-
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.</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..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..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..RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.</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",);
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简单的增删改查的更多相关文章
- springboot(三 使用mybatis +springboot 完成简单的增删改查)
先说一些注解: @EnableAutoConfiguration 可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器 ...
- hibernate简单的增删改查
获取当前线程的session protected Session getSession() { return sessionFactory.getCurrentSession(); } 增加:save ...
- MyBatis学习--简单的增删改查
jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...
- springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能
转自:https://blog.csdn.net/thinkingcao/article/details/52472252 C 所用到的jar包 数据库表 数据库表就不用教大家了,一张表,很简 ...
- salesforce 零基础学习(五十一)使用 Salesforce.com SOAP API 实现用户登录以及简单的增删改查(JAVA访问salesforce)
此篇请参看:https://resources.docs.salesforce.com/202/latest/en-us/sfdc/pdf/salesforce_developer_environme ...
- 通过JDBC进行简单的增删改查
通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...
- MyBatis简单的增删改查以及简单的分页查询实现
MyBatis简单的增删改查以及简单的分页查询实现 <? xml version="1.0" encoding="UTF-8"? > <!DO ...
- 初试KONCKOUT+WEBAPI简单实现增删改查
初试KONCKOUT+WEBAPI简单实现增删改查 前言 konckout.js本人也是刚刚接触,也是初学,本文的目的是使用ko和asp.net mvc4 webapi来实现一个简单增删改查操作.Kn ...
- MVC3.0+knockout.js+Ajax 实现简单的增删改查
MVC3.0+knockout.js+Ajax 实现简单的增删改查 自从到北京入职以来就再也没有接触MVC,很多都已经淡忘了,最近一直在看knockout.js 和webAPI,本来打算采用MVC+k ...
随机推荐
- (转) SolrCloud之分布式索引及与Zookeeper的集成
http://blog.csdn.net/ebay/article/details/46549481 作者:Wang, Josh 一.概述 Lucene是一个Java语言编写的利用倒排原理实现的文本检 ...
- Memcached 在Linux上的安装
1.安装libevent wget https://github.com/libevent/libevent/releases/download/release-2.1.8-stable/libeve ...
- Ubuntu 18.04 如何固定图标到任务栏
参考 https://blog.csdn.net/u014160286/article/details/81631863
- Cesium学习笔记(四)Camera ----http://blog.csdn.net/hobhunter/article/details/74909641
Cesium 相机控制场景中的视野.操作相机的方法有很多,如旋转,缩放,平移和飞到目的地.Cesium具有默认的鼠标和触摸事件处理程序与相机进行交互,还有一个API以编程方式操纵相机. 我们可以使用该 ...
- chrome浏览器处理本地Ajax跨域
chrome浏览器下 项目开发过程中,用到了Ajax异步请求.若将项目放在本地服务器中,通过localhost访问文件,不会报错.若直接通过file://访问文件就会报错. 报错信息: XMLHttp ...
- Cat VS Dog HDU_3829(最大独立集最大匹配)
Cat VS Dog 题意:一群小朋友去动物园,如果每个小朋友喜欢的动物是猫,那么不喜欢的动物一定是狗,反之也是.现在动物园的管理者要拿走一些动物,如果拿走的是某个小朋友不喜欢的动物,那这个小朋友就非 ...
- python爬虫12 | 爸爸,他使坏,用动态的 Json 数据,我要怎么搞?
在前面我们玩了好多静态的 HTML 想必你应该知道怎么去爬这些数据了 但还有一些常见的动态数据 比如 商品的评论数据 实时的直播弹幕 岛国动作片的评分 等等 这些数据是会经常发生改变的 很多网站就会用 ...
- C#学习笔记_08_面向对象
08_面向对象 面向对象:一种看待问题解决问题的思维方式,着眼点在于找到一个能够帮助我们解决问题的实体,然后委托这个实体来帮我们解决问题:(在面向对象之前你要有一个女朋友,否则代码会经常出现bug) ...
- BZOJ 4278 [ONTAK2015]Tasowanie (后缀数组)
题目链接: https://www.lydsy.com/JudgeOnline/problem.php?id=4278 题解: 居然把后缀数组写成n^2的..我真厉害.. 想了无数种方法,最后发现就是 ...
- VS2017git 提交提示错误 Git failed with a fatal error.
具体错误信息:Git failed with a fatal error.error: open("ConsoleApp1/.vs/ConsoleApp1/v15/Server/sqlite ...