数据库的连接创建、释放频繁造成系统资源浪费,使用数据库连接池可解决
SQL语句在代码中硬编码,代码维护不易,在应用中Sql变化大,一旦变动就要修改代码
使用preparedStatement时,占位符?可能接收硬编码,当条件子句不一定时,占位符可多可少。改完sql要改代码,维护不易
对结果集解析存在硬编码,将数据库记录封装成pojo对象解析方便
上面的问题借助DBUtils或Spring中自带的数据库操作框架JdbcTemplate,解决一定程度的问题
真正解决问题的是:
- Jpa
- MyBatis
CREATE DATABASE `stumsg`;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int NOT NULL,
`name` varchar(45) DEFAULT NULL,
`sex` varchar(45) DEFAULT NULL,
`number` varchar(45) DEFAULT NULL,
`address` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `student` VALUES
(1,'李继勇','男','12337623816','山东省'),
(2,'张航','男','23839203813','海南省'),
(3,'赵涛','男','27301820912','安徽省'),
(4,'张美娜','女','38201739103','云南省'),
(5,'夏佳宁','女','18392748372','新疆省'),
(6,'金斐','女','17392640933','山东省');
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 解决maven资源过滤问题 -->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>false</filtering>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/stumsg?useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 改为映射文件XxxMapper.xml所在的路径 -->
<mapper resource="com/ma/mapper/StudentMapper.xml"/>
</mappers>
</configuration>
package com.ma.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* @author :Myy
* @date :Created in 2021/9/5 14:20
*/
public class Utils {
// 提升作用域
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e) {
e.printStackTrace();
}
}
// 获取
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
package com.ma.pojo;
/**
* @author :Myy
* @date :Created in 2021/9/5 11:25
*/
public class Student {
// 属性
// 构造方法
// 重写toString方法
// Getter方法 Setter方法
}
package com.ma.mapper;
import com.ma.pojo.Student;
import java.util.List;
/**
* @author :Myy
* @date :Created in 2021/9/5 11:27
*/
public interface StudentMapper {
List<Student> selectAllStudent();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 绑定一个mapper接口 -->
<mapper namespace="com.ma.mapper.StudentMapper">
<!-- id填写持久层的方法名 -->
<!-- 返回结果集路径是持久层 -->
<select id="selectAllStudent" resultType="com.ma.pojo.Student">
select * from student ;
</select>
</mapper>
快捷方法:
package com.ma.dao;
import junit.framework.TestCase;
/**
* @author :Myy
* @date :Created in 2021/9/5 15:15
*/
public class StudentMapperTest extends TestCase {
@Test
public void testSelectAllStudent() {
SqlSession sqlSession = Utils.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = studentMapper.selectAllStudent();
// 获取数据
for (Student studentList : studentLists) {
System.out.println(studentList);
}
sqlSession.close();
}
}
注意:
- xml文件里不要有中文注释
<insert id="insertStudent" parameterType="com.ma.pojo.Student">
insert into student (id,name,sex,number,address)
values (#{id},#{name},#{sex},#{number},#{address})
</insert>
int insertStudent(Student student);
@Test
public void testInsertStudent() {
SqlSession sqlSession = MapperUtils.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.insertStudent(new Student(7,"李文博", "男", "12037281909", "湖南省"));
// 提交事务
sqlSession.commit();
// 关闭资源
sqlSession.close();
}
<select id="selectAllStudent" resultType="com.ma.pojo.Student">
select * from student
</select>
<select id="selectStudentById" parameterType="int" resultType="com.ma.pojo.Student">
select * from student where id = #{id}
</select>
List<Student> selectAllStudent();
Student selectStudentById(int id);
@Test
public void testSelectAllStudent() {
SqlSession sqlSession = MapperUtils.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentLists = studentMapper.selectAllStudent();
for (Student studentList : studentLists) {
System.out.println(studentList);
}
sqlSession.close();
}
@Test
public void testSelectStudentById() {
SqlSession sqlSession = MapperUtils.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = studentMapper.selectStudentById(1);
System.out.println(student);
sqlSession.close();
}
<update id="updateStudent" parameterType="com.ma.pojo.Student">
update student set
name = #{name},
sex = #{sex},
number = #{number},
address = #{address}
where id = #{id}
</update>
int updateStudent(Student student);
@Test
public void testUpdateStudent() {
SqlSession sqlSession = MapperUtils.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.updateStudent(new Student(7, "王明", "女", "18393048087", "浙江省"));
sqlSession.commit();
sqlSession.close();
}
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- Mysql数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/stumsg?useSSL=false&serverTimezone=UTC"
userId="root"
password="123456" />
<!-- 默认为false,把JDBC DECIMAL 和NUMERIC类型解析为Integer,为true时 把JDBC DECIMAL 和NUMERIC类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成POJO类的位置 -->
<javaModelGenerator
targetPackage="com.ma.pojo" targetProject="F:/MyBatisLearn/mybatis_reverse/src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.ma.mapper"
targetProject="F:/MyBatisLearn/mybatis_reverse/src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetProject:mapper接口生成的的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.ma.dao" targetProject="F:/MyBatisLearn/mybatis_reverse/src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据表 有几个表写几个 -->
<table tableName="数据表名"></table>
<table tableName="数据表名"></table>
</context>
</generatorConfiguration>
注意事项:
- targetPackage里写包名
- targetProject里写生成代码所在的路径
import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.internal.DefaultShellCallback;import java.io.File;import java.util.*;/** * @author :Myy * @date :Created in 2021/9/10 10:53 */public class GeneratorSqlmap {
public void generator() throws Exception {
List<String> warnings = new ArrayList<String>(); boolean overwrite = true; // 指定配置文件 File configFile = new File("mybatis_reverse/src/main/resources/config/genertorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } // 执行main方法以生成代码 public static void main(String[] args) { try { GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap(); generatorSqlmap.generator(); } catch (Exception e) { e.printStackTrace(); } }}
上一篇文章我们实现了一个模拟的hwmon device,且针对该hwmon device的属性访问操作均是借助sysfs file(我们创建了4个通道温度的sysfs文件temp1_input、temp2_input…),而sysfs file则是我们的虚拟驱动程序借助我们创建device_attribute实现的,然后进行了hwmon_device的注册,相对而言hwmon子系统倒没有提供太多的帮助,而在linux 4.x的版本(4.14已经支持)中,则对hwmon子系统中进行了丰富,针对te...
课程目标CO1: 学习并掌握图像分类项目的语法基础、深度学习基础CO2: 通过学习和完成图像分类项目 ,初步掌握应用 python 语言调用模型并完成特定图像分类的能力。CO3 :培养学生在开展实践过程中的分工协作,交流表达能力CO4 : 培养学生对实践工作内容的文档写作能力。人工智能基础人工智能是什么,和图像分类项目的关系是什么人工智能( Artificial Intelligence ) ,英文缩写为 AI 。它是研究、开发用于 模拟、延伸和扩展人的智能 ...
参考:http://blog.csdn.net/nicky_lyu/article/details/53181434http://blog.csdn.net/u012841667/article/details/53436615http://www.cnblogs.com/zjutzz/p/6034408.htmlstep 1. 安装常用的dependencies
Scala IDE for Eclipse 之spark scala语言开发环境搭建------遇到问题记录2016年12月29日 19:37:551922人阅读 评论(0) 收藏 举报 分类:Spark(10) 版权声明:你好,欢迎来到我的博客。 https://blog.csdn.net/zwyjg/article/details/53931573spark开发都建议使用idea,但是使用不...
在AIO中,服务端通过asynchronousServerSocketChannel.accept(this,newAcceptCompletionHandler());的方式接收客户端的连接,那它是怎么做的呢,我们做下源码分析。这个accept方法进入了实现类AsynchronousServerSocketChannelImpl的accept方法,如下: pub
詹金斯搭建 您有兴趣跟踪开源云中正在发生的事情吗? Opensource.com是您在开源云基础设施项目OpenStack中获取新闻的来源。 Web上的OpenStack 关于OpenStack,有很多有趣的东西。 以下是一些我们的最爱的示例: 没有Jenkins,只有Zuul :OpenStack最终关闭了它的最后一个Jenkins主机,现在完全使用Zuul来自动化其测试。 ...
前言最近读完的一本书,记录下随笔,留下对自己的影响。作为一个入行近10年的十年程序员,这本书中作者对待软件这个职业之外的观点看法,确实很多是我们不经常考虑的。比如健身,你的身体就是你灵魂的真实写照。如何选择饮食,如何控制卡路里,带你入门,引起注意。比如如何提前退休,如何投资,讲解基本的投资知识和经济学原理。对于职业生涯,经常面试看看自己在行业中的位置,番茄工作法,提高工作效率等等。心得绝不要做他人都在做的事。做事情、工作思考目标,目标是什么?关注人际交往能力,虽然是程序员,但不仅仅是跟电脑打交道
Windows10 不知道从什么时候开始不再支持PL2303HXA USB转串口芯片了,无法在线获取驱动,需要手动安装。步骤如下:下载驱动:点击下载链接确认USB转串口已经从电脑拔出双击exe安装驱动根据弹窗提示插入USB转串口继续,完成安装安装完成之后可能还有感叹号,重启电脑即可...
问题描述:jenkins执行的robot用例,打开log.html时显示: 备注:浏览器版本已经是最新. -场景:用firefox和chrome打开jenkins robot项目的log.html,如上图所示,但是用IE8可以打开log,而IE8打开jenkins会有异常报错;解决方法: 参考:http://blog.csdn.net/max229max/article/details/5
注重这些细节有几个好处:1. 好的命名规范可以使得写出来的程序更容易被别人理解,更好维护。当然也易于自己理解,以便日后扩展。 同时,也使程序更规范和专业。 在这个人性化横行的今天,我们的Java命名规范也应该注重体验。2. 了解命名规范,可以更好的学习和记忆 Java 类库中的类和函数等。3. 在命名规范里有很多都涉及到英文的,可以促进英文学习。 比如: numberMax, MaxNumber和maxNumber都是有区别的。 maxNumber可能是属性名; MaxNumber一般是类名; n
1. 模板工程的创建(超级详细版)1.1创建工程目录良好的工程结构能让文件的管理更科学,让开发更容易更方便,希望大家养成良好的习惯,使用具有合理结构的工程目录,当你着手于较大的软件项目时,类别分明,层次合理的工程目录结构会让你的开发管理化繁为简。(1)首先在一个目录下创建主文件夹,名字按需求取,这里取名为:(0)工程模板(2)在该文件夹里分别建立名字为Project和Sou
fairseq 安装报错问题Running setup.py install for fairseq ... errorERROR: Command errored out with exit status 1:command: /Users/superman/anaconda/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/3h/3v_dnwl95tl9k9swb