SpringBoot-JPA入门
SpringBoot-JPA入门
JPA就是Spring集成了hibernate感觉。
注解,方法仓库(顾名思义的方法,封装好了,还有自定义的方法)。
案例:
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
#指定数据库连接池类型
type: org.apache.commons.dbcp2.BasicDataSource
dbcp2:
#最大等待连接中的数量,设0位没有限制
max-idle: 10
#最大连接活动数
max-total: 50
#最大等待毫秒数,单位为ms,超过时间会出错误信息
max-wait-millis: 10000
#数据库连接初始化连接数
initial-size: 5
jpa:
database-platform: org.hibernate.dialect.MySQLDialect
show-sql: true
hibernate:
ddl-auto: update
package com.lanqiao.springbootjdbc.pojo; import com.lanqiao.springbootjdbc.converter.SexConverter;
import com.lanqiao.springbootjdbc.enumeration.SexEnum;
import lombok.Data; import javax.persistence.*; /**
* @author DeepSleeping
* @date 2019/5/28 16:17
* @description
*/
@Data
@Entity(name = "user")
@Table(name = "t_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id = null;
@Column(name = "user_name")
private String userName = null;
@Convert(converter = SexConverter.class)
private SexEnum sex = null;
private String note = null;
}
package com.lanqiao.springbootjdbc.dao; import com.lanqiao.springbootjdbc.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import java.util.List; public interface JpaUserRepository extends JpaRepository<User, Long> { @Query("from user where user_name like concat('%',?1,'%') and note like concat('',?2,'%') ")
public List<User> findUsers(String userName, String note); /**
* @description 按用户名称模糊查询
* @author DeepSleeping
* @date 2019/5/28 19:40
*/
List<User> findByUserNameLike(String userName); /**
* @description 根据主键查询
* @author DeepSleeping
* @date 2019/5/28 19:41
*/
User getUserById(Long id); /**
* @description 按照用户名称或者备注进行模糊查询
* @author DeepSleeping
* @date 2019/5/28 19:42
*/
List<User> findByUserNameLikeOrNoteLike(String userName, String note);
}
package com.lanqiao.springbootjdbc.service.impl; import com.lanqiao.springbootjdbc.enumeration.SexEnum;
import com.lanqiao.springbootjdbc.pojo.User;
import com.lanqiao.springbootjdbc.service.JdbcTmplUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List; /**
* @author DeepSleeping
* @date 2019/5/28 16:28
* @description
*/
@Service
public class JdbcTmplUserServiceImpl implements JdbcTmplUserService { @Autowired
private JdbcTemplate jdbcTemplate; /**
* @description 获取映射关系
* @author DeepSleeping
* @date 2019/5/28 16:29
*/
private RowMapper<User> getUserMapper() {
RowMapper<User> userRowMapper = (ResultSet rs, int rownum) -> {
User user = new User();
user.setId(rs.getLong("id"));
user.setUserName(rs.getString("user_name"));
int setId = rs.getInt("sex");
SexEnum sex = SexEnum.getEnumById(setId);
user.setSex(sex);
user.setNote(rs.getString("note"));
return user;
};
return userRowMapper;
} @Override
public User getUser(Long id) {
String sql = "select id,user_name,sex,note from t_user where id = ?";
//参数
Object[] params = new Object[]{id};
User user = jdbcTemplate.queryForObject(sql, params, getUserMapper());
return user;
} @Override
public List<User> findUsers(String userName, String note) {
String sql = "select id,user_name,sex,note from t_user where user_name like concat('%',?,'%') and note like concat('%',?,'%')";
Object[] params = new Object[]{userName, note};
List<User> userList = jdbcTemplate.query(sql, params, getUserMapper());
return userList;
} @Override
public int insertUser(User user) {
String sql = "insert into t_user (user_name,sex,note) values(?,?,?)";
return jdbcTemplate.update(sql, user.getNote(), user.getSex().getId(), user.getNote());
} @Override
public int updateUser(User user) {
String sql = "update t_user set user_name = ?,sex=?,note=? where id = ?";
return jdbcTemplate.update(sql, user.getUserName(), user.getSex().getId(), user.getNote(), user.getId());
} @Override
public int deleteUser(Long id) {
String sql = "delete from t_user where id = ?";
return jdbcTemplate.update(sql, id);
} public User getUser2(Long id) {
User result = this.jdbcTemplate.execute((Statement stmt) -> {
String sql1 = "select count(*) total from t_user where id = " + id;
ResultSet rs1 = stmt.executeQuery(sql1);
while (rs1.next()) {
int total = rs1.getInt("total");
System.out.println(total);
} String sql2 = "select id,user_name,sex,note from t_user where id = " + id;
ResultSet rs2 = stmt.executeQuery(sql2);
User user = null;
while (rs2.next()) {
int rowNum = rs2.getRow();
user = getUserMapper().mapRow(rs2, rowNum);
}
return user;
});
return result;
}
}
package com.lanqiao.springbootjdbc.controller; import com.lanqiao.springbootjdbc.dao.JpaUserRepository;
import com.lanqiao.springbootjdbc.pojo.User;
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.ResponseBody;
import sun.nio.cs.US_ASCII; import java.util.List;
import java.util.Optional; /**
* @author DeepSleeping
* @date 2019/5/28 17:05
* @description
*/
@Controller
@RequestMapping("/jpa")
public class JpaController {
//注入jpa接口,这里不需要使用实现类 @Autowired
private JpaUserRepository jpaUserRepository = null; @RequestMapping("/getUser")
@ResponseBody
public User getUser(Long id) {
//使用JPA接口查询对象
Optional<User> user = jpaUserRepository.findById(id);
return user.get();
} @RequestMapping("/getUserById")
@ResponseBody
public User getUserById(Long id) {
//使用JPA接口查询对象
User user = jpaUserRepository.getUserById(id);
return user;
} @RequestMapping("/findByUserNameLike")
@ResponseBody
public List<User> findByUserNameLike(String userName) {
//使用JPA接口查询对象
List<User> userList = jpaUserRepository.findByUserNameLike("%" + userName + "%");
return userList;
} @RequestMapping("/findByUserNameOrNoteLike")
@ResponseBody
public List<User> findByUserNameOrNoteLike(String userName, String note) {
String userNameLike = "%" + userName + "%";
String noteLike = "%" + note + "%";
//使用JPA接口查询对象
List<User> userList = jpaUserRepository.findByUserNameLikeOrNoteLike(userNameLike, noteLike);
return userList;
}
}

package com.lanqiao.springbootjdbc.converter; import com.lanqiao.springbootjdbc.enumeration.SexEnum; import javax.persistence.AttributeConverter; /**
* @author DeepSleeping
* @date 2019/5/28 17:00
* @description
*/
public class SexConverter implements AttributeConverter<SexEnum, Integer> { /**
* @description 将枚举转换为数据库列
* @author DeepSleeping
* @date 2019/5/28 17:01
*/
@Override
public Integer convertToDatabaseColumn(SexEnum sex) {
return sex.getId();
} @Override
public SexEnum convertToEntityAttribute(Integer id) {
return SexEnum.getEnumById(id);
}
}
package com.lanqiao.springbootjdbc; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication
@EnableJpaRepositories(basePackages = "com.lanqiao.springbootjdbc.dao")
@EntityScan(basePackages = "com.lanqiao.springbootjdbc.pojo")
public class SpringbootJdbcApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootJdbcApplication.class, args);
} }
参考书籍:《深入浅出SpringBoot2.x》
SpringBoot-JPA入门的更多相关文章
- SpringBoot Jpa入门案例
版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons) 我们先来了解一下是什么是springboot jpa,springboo ...
- SpringData 基于SpringBoot快速入门
SpringData 基于SpringBoot快速入门 本章通过学习SpringData 和SpringBoot 相关知识将面向服务架构(SOA)的单点登录系统(SSO)需要的代码实现.这样可以从实战 ...
- SpringBoot 初入门
SpringBoot 初入门 关于介绍什么之类的就不讲了,主要做一下学习记录. 1. 启动方式 IDEA 启动 命令行启动: mvn spring-boot:run 部署到服务器启动: 先进行打包, ...
- SpringBoot基础篇-SpringBoot快速入门
SpringBoot基础 学习目标: 能够理解Spring的优缺点 能够理解SpringBoot的特点 能够理解SpringBoot的核心功能 能够搭建SpringBoot的环境 能够完成applic ...
- Spring Data Jpa 入门学习
本文主要讲解 springData Jpa 入门相关知识, 了解JPA规范与Jpa的实现,搭建springboot+dpringdata jpa环境实现基础增删改操作,适合新手学习,老鸟绕道~ 1. ...
- IDEA SpringBoot+JPA+MySql+Redis+RabbitMQ 秒杀系统
先放上github地址:spike-system,可以直接下载完整项目运行测试 SpringBoot+JPA+MySql+Redis+RabbitMQ 秒杀系统 技术栈:SpringBoot, MyS ...
- JPA入门例子(采用JPA的hibernate实现版本) 转
JPA入门例子(采用JPA的hibernate实现版本) jpahibernate数据库jdbcjava框架(1).JPA介绍: JPA全称为Java Persistence API ,Java持久化 ...
- 补习系列(19)-springboot JPA + PostGreSQL
目录 SpringBoot 整合 PostGreSQL 一.PostGreSQL简介 二.关于 SpringDataJPA 三.整合 PostGreSQL A. 依赖包 B. 配置文件 C. 模型定义 ...
- 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础授权权限
上一篇<[原]无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限>介绍了实现Shiro的基础认证.本篇谈谈实现 ...
- 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限
开发环境搭建参见<[原]无脑操作:IDEA + maven + SpringBoot + JPA + Thymeleaf实现CRUD及分页> 需求: ① 除了登录页面,在地址栏直接访问其他 ...
随机推荐
- Flutter移动电商实战 --(25)列表页_使用Provide控制子类-1
主要是二级分类的UI布局 生成我们的右侧动态类 定义list变量 开始写里面的子项,把每一个小的写了 再拼成一个大的 这样我们的小类就写完了 开始写我的大类别:是一个横向的ListView.写横向的L ...
- python 调用github的api,呈现python的受欢迎的程度
1 使用api调用数据: 在浏览器的地址栏中输入: https://api.github.com/search/repositories?q=language:python&sort=star ...
- JavaWeb——Get、Post请求中文乱码问题
最近在重温JavaWeb基础内容,碰到了之前也时常遇到的中文乱码问题,想着反正是经常要处理的,不如当即就把它整理出来放在博客里,省得遇到时再去到处搜. 1. Post请求乱码的解决方案: 手工创建一个 ...
- Android 屏幕适配之dimens适配
Android 屏幕适配之dimens适配 转 https://blog.csdn.net/github_2011/article/details/72636851 在过去多个项目中一直使用 ...
- LevelListDrawable
用来管理一组Drawable的,我们可以为里面的drawable设置不同的level, 当他们绘制的时候,会根据level属性值获取对应的drawable绘制到画布上,根节点 为:<level- ...
- sql控制流if()、case when then
tb_user: 1.if (expr1,expr2,expr3) #如果expr1成立,则返回expr2,否则返回expr3示例:select name, if (sex=1,'男','女') ...
- Equals和GetHashCode
Q:2个方法同时被重写的场景? A:Dictionary或HashTable的key使用时,必须重写这两个方法; 因为:根据key取值的时候也是把key转换成HashCode并且验证Equals后再取 ...
- 分析UIS-RNN源代码的代码规范和风格
结合工程实践选题相关的一套源代码,根据其编程语言或项目特点,分析其在源代码目录结构.文件名/类名/函数名/变量名等命名.接口定义规范和单元测试组织形式等方面的做法和特点: 列举哪些做法符合代码规范和风 ...
- C#使用MPI进行高性能计算
MPI.NET是用于Microsoft.NET环境的高性能.易于使用的消息传递接口(MPI)实现.mpi是编写在分布式内存系统(如计算集群)上运行的并行程序的事实上的标准,并且得到了广泛的实现.大多数 ...
- mysql写存储过程根据时间变化增加工龄
在工作中遇到要程序根据时间自动增加工龄的需求. php没办法自己发起请求,又不想在服务器上写计划任务crontab,通过用户请求来更改又不能保证用户会去操作. 用数据库的存储过程和事件来完成. 数据库 ...