Mybatis学习总结:框架简介+传统JDBC连接数据库+Mybatis操作数据库的两个简单应用
Mybatis框架简介:
Mybatis是一种支持普通SQL查询,存储过程和高级映射的持久层框架(懂不懂先拿小本本记下来了????),该框架几乎消除了所有的JDBC代码和参数的手工设置以及对结果集的检索和封装,Mybatis可以用简单的XML或注解用于配置和原始映射,将接口和普通的Java对象映射成为数据库中的记录
为对比出与传统jdbc的区别,先用传统方式连接数据库
给出一份查询planegame数据库代码:
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class ConnectMysql {
public static void main(String[] args) {
//声明三个对象
Connection connection = null;
PreparedStatement preparedStatement =null;
ResultSet resultset =null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//要连接的数据库名
String database ="planegame";
//完整地址
String url = "jdbc:mysql://localhost:3306/"+database;
//创建连接
connection =(Connection) DriverManager.getConnection(url,"root","");
//sql语句
String sql ="select * from planegame where username=?";
preparedStatement =(PreparedStatement) connection.prepareStatement(sql);
preparedStatement.setString(1, "12");
//查询并返回结果
resultset=preparedStatement.executeQuery();
//输出结果
while(resultset.next()) {
System.out.println("该用户密码是:"+resultset.getString("password")+"\n用户在线时间:"+resultset.getString("time"));
}
}catch(Exception e) {
System.out.println("hahahha");
e.printStackTrace();
}
finally {
//释放资源
if(resultset!=null) {
try {
resultset.close();
}catch(SQLException e) {
System.out.println("qqq");
e.printStackTrace();
}
}
}
}
}
步骤可总结为:
•1、 加载数据库驱动
•2、 创建并获取数据库链接
•3、 创建jdbc statement对象
•4、 设置sql语句
•5、 设置sql语句中的参数(使用preparedStatement)
•6、 通过statement执行sql并获取结果
•7、 对sql执行结果进行解析处理
•8、 释放资源(resultSet、preparedstatement、 connection)
这种方式连接数据库有些不足:
(1)数据库创建连接是占用资源的,频繁创建连接释放连接会造成对资源的浪费,造成系统性能的下降
(2)sql语句在代码中存在硬编码,造成代码不容易维护,sql语句一变动,就得需要改变Java代码
(3)用peparedStatement对象向占位符传参数也存在硬编码,如果查询语句较多则不利于维护
(4)对结果集的遍历也存在硬编码,sql语句变化,造成解析语句变化,如果将结果封装成pojo对象解析比较方便
Mybatis框架将大量的sql语句分离出来,这样就避免了上述问题,将sql语句单独封装在一个文件里,这样sql语句变化只需在此文件里修改即可。
建立第一个Mybatis项目来回忆:
1、需要导入Mybatis.jar+mysql驱动包(百度网盘提供)
链接:https://pan.baidu.com/s/12jzCA5E8yXU6RLn-kfKFFg
提取码:s87n
项目结构图:
2、建库+建表:
使用navicat可视化操作数据库工具
create database mybatis;
use mybatis;
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);
INSERT INTO users(NAME, age) VALUES('Tom', 12);
INSERT INTO users(NAME, age) VALUES('Jack', 11);
3、添加mybatis的配置文件conf.xml,此文件放在src包下
<?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>
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mybatis_test/userMapper.xml"/>
</mappers>
</configuration>
4、创建数据库配置文件db.perporties:
driver=com.mysql.jdbc.Driver
url =jdbc:mysql://localhost:3306/mybatis
username=root
password=
该文件在conf.xml中通过<properties></properties> 被引用
4、如果你使用了日志文件还需要写一个log4j.xml文件(这里的代码通常不变,直接复制即可)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="debug" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
5、编写实体类User:
package mybatis_test;
public class User {
private int age;
private String name;
private int id;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "User [age=" + age + ", name=" + name + ", id=" + id + "]";
}
public User(int age, String name, int id) {
super();
this.age = age;
this.name = name;
this.id = id;
}
public User() {
super();
}
}
普及一个eclipse使用小技巧????
6、定义操作表的usermapper.xml文件并注册到conf.xml文件中:
<?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 namespace="mybatis_test/User">
<!--写一个查询语句-->
<select id="getUser" parameterType="int"
resultType="mybatis_test.User">
select * from users where id=#{id}
</select>
</mapper>
注册到conf.xml里:
<mappers>
<mapper resource="mybatis_test/userMapper.xml"/>
</mappers>
7、编写测试类:
package mybatis_test;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Test {
public static void main(String[] args) throws IOException {
String resources ="conf.xml";
//加载配置文件
Reader reader = Resources.getResourceAsReader(resources);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
//映射sql的标识字符串
String statement = "mybatis_test/User"+".getUser";
//执行查询返回一个唯一user对象的sql
User user = session.selectOne(statement, 1);
System.out.println(user);
}
}
代码执行结果:
测试mybatis第一个项目就完成了。
下面讲述对表的增删改查的实现:
在usermapper文件中增加增删改查语句:
<?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 namespace="mybatis_test1">
<insert id="insert_user" parameterType="mybatis_test.User">
insert into users(name,age) values(#{name},#{age});
</insert>
<delete id="delete_user" parameterType="int">
delete from users where id=#{id}
</delete>
<update id="update_user" parameterType="mybatis_test.User">
update users set name=#{name} ,age=#{age} where id=#{id}
</update>
<select id="select_user" parameterType="int" resultType="mybatis_test.User">
select * from users where id=#{id}
</select>
<select id="select_alluser" parameterType="int" resultType="mybatis_test.User">
select * from users
</select>
</mapper>
编写测试类时,可用@Test注释注释为测试方法,利用junit单元测试
因为在每个测试方法里都需要写这三个语句,所以将它封装为一个类
MybatisUtils类:
package mybatis_test1;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtils {
public static SqlSessionFactory getFactory() {
String resources = "conf.xml";
InputStream is = Test1.class.getClassLoader().getResourceAsStream(resources);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
return factory;
}
}
然后测试类:
package mybatis_test1;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
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 org.junit.Test;
import mybatis_test.User;
public class Test1 {
@Test
public void TestAdd() {
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session =factory.openSession();
String statement="mybatis_test1.insert_user";
int insert = session.insert(statement,new User(-1,"XY",23));
session.commit();
System.out.println(insert);
}
@Test
public void TestDelete() {
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session =factory.openSession();
String statement="mybatis_test1.delete_user";
int delete = session.delete(statement,5);
session.commit();
System.out.println(delete);
}
@Test
public void TestUpdate() {
SqlSessionFactory factory =MybatisUtils.getFactory();
SqlSession session =factory.openSession();
String statement = "mybatis_test1.update_user";
int update = session.update(statement, new User(7,"SWT",23));
session.commit();
System.out.println(update);
}
@Test
public void TestSelect() throws IOException {
// SqlSessionFactory factory =MybatisUtils.getFactory();
// SqlSession session =factory.openSession();
String resources ="conf.xml";
//加载配置文件
Reader reader = Resources.getResourceAsReader(resources);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
String statement = "mybatis_test1.select_user";
User user =session.selectOne(statement,6);
session.commit();
System.out.println(user);
}
@Test
public void TestSelectAll() {
SqlSessionFactory factory =MybatisUtils.getFactory();
SqlSession session =factory.openSession();
String statement = "mybatis_test1.select_alluser";
List<User> list =session.selectList(statement);
session.commit();
System.out.println(list);
}
}
在实体类中如果你提供了有参数的构造函数,那么你就需要提供无参数的构造函数(默认是提供无参构造函数的,但写了有参构造函数无参构造函数不再被提供,所以需要手动提供),因为没有无参构造函数,select查到数据后无法封装到实体对象中。
运行结果:
MybatisCRUD操作数据库完成。
我在想怎么总结这个Mybatis才好,大多都是通过代码来完成的,想静静????
上一篇: php feof 函数