当前位置: 首页 > 编程日记 > 正文

SpringBoot-JPA入门

SpringBoot-JPA入门

JPA就是Spring集成了hibernate感觉。

注解,方法仓库(顾名思义的方法,封装好了,还有自定义的方法)。

案例:

spring:datasource:url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCusername: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driver#指定数据库连接池类型type: org.apache.commons.dbcp2.BasicDataSourcedbcp2:#最大等待连接中的数量,设0位没有限制max-idle: 10#最大连接活动数max-total: 50#最大等待毫秒数,单位为ms,超过时间会出错误信息max-wait-millis: 10000#数据库连接初始化连接数initial-size: 5jpa:database-platform: org.hibernate.dialect.MySQLDialectshow-sql: truehibernate: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 {@Autowiredprivate 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;}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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());}@Overridepublic 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());}@Overridepublic 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接口,这里不需要使用实现类
@Autowiredprivate JpaUserRepository jpaUserRepository = null;@RequestMapping("/getUser")@ResponseBodypublic User getUser(Long id) {//使用JPA接口查询对象Optional<User> user = jpaUserRepository.findById(id);return user.get();}@RequestMapping("/getUserById")@ResponseBodypublic User getUserById(Long id) {//使用JPA接口查询对象User user = jpaUserRepository.getUserById(id);return user;}@RequestMapping("/findByUserNameLike")@ResponseBodypublic List<User> findByUserNameLike(String userName) {//使用JPA接口查询对象List<User> userList = jpaUserRepository.findByUserNameLike("%" + userName + "%");return userList;}@RequestMapping("/findByUserNameOrNoteLike")@ResponseBodypublic 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*/@Overridepublic Integer convertToDatabaseColumn(SexEnum sex) {return sex.getId();}@Overridepublic 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》

转载于:https://www.cnblogs.com/deepSleeping/p/10939860.html

相关文章:

PCA、LDA、MDS、LLE、TSNE等降维算法的Python实现

整理 | 夕颜出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;【导读】网上关于各种降维算法的资料参差不齐&#xff0c;但大部分不提供源代码。近日&#xff0c;有人在 GitHub 上整理了一些经典降维算法的 Demo(Python)集合&#xff0c;同时给出了参考资料的链接。PCA…

C++11中enum class的使用

枚举类型(enumeration)使我们可以将一组整型常量组织在一起。和类一样&#xff0c;每个枚举类型定义了一种新的类型。枚举属于字面值常量类型。 C包含两种枚举&#xff1a;限定作用域的和不限定作用域的。这里主要介绍限定作用域的。不限定作用域的使用可以参考&#xff1a; ht…

Windows下Mysql主从配置(Mysql5.5)

主数据库IP:192.168.3.169从数据库IP:192.168.3.34主数据库配置my.inin&#xff1a;在[mysqld]下添加配置数据&#xff1a;server-id1 #配一个唯一的ID编号&#xff0c;1至32。log-binmysql-bin #二进制文件存放路径#设置要进行或不要进行主从复制的数据库名&#xff0c;同…

K-最近邻法(KNN) C++实现

关于KNN的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78464169 这里给出KNN的C实现&#xff0c;用于分类。训练数据和测试数据均来自MNIST&#xff0c;关于MNIST的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/deta…

AI大佬“互怼”:Bengio和Gary Marcus隔空对谈深度学习发展现状

编译 | AI科技大本营编辑部出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;去年以来&#xff0c;由于纽约大学教授 Gary Marcus 对深度学习批评&#xff0c;导致他在社交媒体上与许多知名的 AI 研究人员如 Facebook 首席 AI 科学家 Yann LeCun 进行了一场论战。不止 …

Centos7多内核情况下修改默认启动内核方法

1.1 进入grub.cfg配置文件存放目录/boot/grub2/并备份grub.cfg配置文件 [rootlinux-node1 ~]# cd /boot/grub2/ [rootlinux-node1 grub2]# cp -p grub.cfg grub.cfg.bak [rootlinux-node1 grub2]# ls -ld grub.cfg* -rw-r--r--. 1 root root 5162 Aug 11 2018 grub.cfg -rw-r…

TensorRT Samples: MNIST

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551以下是参考TensorRT 2.1.2中的sampleMNIST.cpp文件改写的实现对手写数字0-9识别的测试代码&#xff0c;各个文件内容如下&#xff1a;common.hpp:#ifndef FBC_TENSORRT_TE…

网红“AI大佬”被爆论文剽窃,Jeff Dean都看不下去了

作者 | 夕颜、Just出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;【导读】近日&#xff0c;推特上一篇揭露 YouTube 网红老师 Siraj Raval 新发表论文涉抄袭其他学者的帖子引起了讨论。揭露者是曼彻斯特大学计算机科学系研究员 Andrew M. Webb&#xff0c;他在 Twit…

数位dp(求1-n中数字1出现的个数)

题意&#xff1a;求1-n的n个数字中1出现的个数。 解法:数位dp&#xff0c;dp[pre][now][equa] 记录着第pre位为now&#xff0c;equa表示前边是否有降数字&#xff08;即后边可不能够任意取&#xff0c;true为没降&#xff0c;true为已降&#xff09;&#xff1b;常规的记忆化搜…

TensorRT Samples: MNIST API

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551 以下是参考TensorRT 2.1.2中的sampleMNISTAPI.cpp文件改写的实现对手写数字0-9识别的测试代码&#xff0c;各个文件内容如下&#xff1a;common.hpp:#ifndef FBC_TENSORR…

免费学习AI公开课:打卡、冲击排行榜,还有福利领取

CSDN 技术公开课 Plus--AI公开课再度升级内容全新策划&#xff1a;贴近开发者&#xff0c;更多样、更落地形式多样升级&#xff1a;线上线下、打卡学习&#xff0c;资料福利&#xff0c;共同交流成长&#xff0c;扫描下方小助手二维码&#xff0c;回复&#xff1a;公开课&#…

Gamma阶段第一次scrum meeting

每日任务内容 队员昨日完成任务明日要完成的任务张圆宁#91 用户体验与优化&#xff1a;发现用户体验细节问题https://github.com/rRetr0Git/rateMyCourse/issues/91#91 用户体验与优化&#xff1a;发现并优化用户体验&#xff0c;修复问题https://github.com/rRetr0Git/rateMyC…

windows 切换 默认 jdk 版本

set JAVA_HOMEC:\jdk1.6.0u24 set PATH%JAVA_HOME%\bin;%PATH%转载于:https://www.cnblogs.com/dmdj/p/3756887.html

TensorRT Samples: GoogleNet

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551 以下是参考TensorRT 2.1.2中的sampleGoogleNet.cpp文件改写的测试代码&#xff0c;文件(googlenet.cpp)内容如下&#xff1a;#include <iostream> #include <t…

Visual Studio Code Go 插件文档翻译

此插件为 Go 语言在 VS Code 中开发提供了多种语言支持。 阅读版本变更日志了解此插件过去几个版本的更改内容。 1. 语言功能 (Language Features) 1.1 智能感知 (IntelliSense) 编码时符号自动补全&#xff08;使用 gocode &#xff09;编码时函数签名帮助提示&#xff08;使用…

资源 | 吴恩达《机器学习训练秘籍》中文版58章节完整开源

整理 | Jane出品 | AI科技大本营&#xff08;ID&#xff1a;rgznai100&#xff09;一年前&#xff0c;吴恩达老师的《Machine Learning Yearning》(机器学习训练秘籍&#xff09;中文版正式发布&#xff0c;经过一年多的陆续更新&#xff0c;近日&#xff0c;这本书的中文版 58…

js字符串加密的几种方法

在做web前端的时候免不了要用javascript来处理一些简单操作&#xff0c;其实如果要用好JQuery, Prototype,Dojo 等其中一两个javascript框架并不简单&#xff0c;它提高你的web交互和用户体验&#xff0c;从而能使你的web前端有非一样的感觉&#xff0c;如海阔凭鱼跃。当然&…

Vue开发入门看这篇文章就够了

摘要&#xff1a; 很多值得了解的细节。 原文&#xff1a;Vue开发看这篇文章就够了作者&#xff1a;RandomFundebug经授权转载&#xff0c;版权归原作者所有。 介绍 Vue 中文网Vue githubVue.js 是一套构建用户界面(UI)的渐进式JavaScript框架库和框架的区别 我们所说的前端框架…

TensorRT Samples: CharRNN

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551 以下是参考TensorRT 2.1.2中的sampleCharRNN.cpp文件改写的测试代码&#xff0c;文件(charrnn.cpp)内容如下&#xff1a;#include <assert.h> #include <str…

Python脚本BUG引发学界震动,影响有多大?

作者 | beyondma编辑 | Jane来源 | CSDN博客近日一篇“A guide to small-molecule structure assignment through computation of (1H and 13C) NMR chemical shifts”文章火爆网络&#xff0c;据作者看到的资料上看这篇论文自身的结果没有什么问题&#xff0c;但是&#xff0c…

C++中public、protect和private用法区别

Calsspig : public animal,意思是外部代码可以随意访问 Classpig : protect animal ,意思是外部代码无法通过该子类访问基类中的public Classpig : private animal ,意思是告诉编译器从基类继承的每一个成员都当成private,即只有这个子类可以访问 转载于:https://blog.51cto.…

TensorRT Samples: MNIST(Plugin, add a custom layer)

关于TensorRT的介绍可以参考&#xff1a;http://blog.csdn.net/fengbingchun/article/details/78469551 以下是参考TensorRT 2.1.2中的samplePlugin.cpp文件改写的通过IPlugin添加一个全连接层实现对手写数字0-9识别的测试代码&#xff0c;plugin.cpp文件内容如下&#xff1a…

AutoML很火,过度吹捧的结果?

作者 | Denis Vorotyntsev译者 | Shawnice编辑 | Jane出品 | AI科技大本营&#xff08;ID&#xff1a;rgznai100&#xff09;【导语】现在&#xff0c;很多企业都很关注AutoML领域&#xff0c;很多开发者也开始接触和从事AutoML相关的研究与应用工作&#xff0c;作者也是&#…

tomcat6 配置web管理端访问权限

配置tomcat 管理端登陆 /apache-tomcat-6.0.35/conf/tomcat-users.xml 配置文件&#xff0c;使用时需要把注释去掉<!-- <!-- <role rolename"tomcat"/> <role rolename"role1"/> <user username"tomcat" password"…

@程序员:Python 3.8正式发布,重要新功能都在这里

整理 | Jane、夕颜出品 | AI科技大本营&#xff08;ID&#xff1a;rgznai100&#xff09;【导读】最新版本的Python发布了&#xff01;今年夏天&#xff0c;Python 3.8发布beta版本&#xff0c;但在2019年10月14日&#xff0c;第一个正式版本已准备就绪。现在&#xff0c;我们都…

TensorRT Samples: MNIST(serialize TensorRT model)

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551 这里实现在构建阶段将TensorRT model序列化存到本地文件&#xff0c;然后在部署阶段直接load TensorRT model序列化的文件进行推理&#xff0c;mnist_infer.cpp文件内容…

【mysql错误】用as别名 做where条件,报未知的列 1054 - Unknown column 'name111' in 'field list'...

需求&#xff1a;SELECT a AS b WHRER b1; //这样使用会报错&#xff0c;说b不存在。 因为mysql底层跑SQL语句时&#xff1a;where 后的筛选条件在先&#xff0c; as B的别名在后。所以机器看到where 后的别名是不认的&#xff0c;所以会报说B不存在。 这个b只是字段a查询结…

C++2年经验

网络 sql 基础算法 最多到图和树 常用的几种设计模式&#xff0c;5以内即可转载于:https://www.cnblogs.com/liujin2012/p/3766106.html

在Caffe中调用TensorRT提供的MNIST model

在TensorRT 2.1.2中提供了MNIST的model&#xff0c;这里拿来用Caffe的代码调用实现&#xff0c;原始的mnist_mean.binaryproto文件调整为了纯二进制文件mnist_tensorrt_mean.binary&#xff0c;测试结果与使用TensorRT调用(http://blog.csdn.net/fengbingchun/article/details/…

142页ICML会议强化学习笔记整理,值得细读

作者 | David Abel编辑 | DeepRL来源 | 深度强化学习实验室&#xff08;ID: Deep-RL&#xff09;ICML 是 International Conference on Machine Learning的缩写&#xff0c;即国际机器学习大会。ICML如今已发展为由国际机器学习学会&#xff08;IMLS&#xff09;主办的年度机器…