一.简述mybatis
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
二.如何使用mydatis
1.引入mysql 和mydatis的jar包
<dependencies>
<!-- mysql驱动jar包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!-- mybatis jar包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependencies>
2.在resources中创建mydatis的配置文件:mydatis.xml
<?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" />
<!--数据源的配置:name的值固定 value的值要根据客户自己修改-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai" />
<property name="username" value="root" />
<property name="password" value="001024" />
</dataSource>
</environment>
</environments>
<!--注册映射文件-->
<mappers>
<mapper resource="mapper/userMapper.xml"/>
</mappers>
</configuration>
3.创建数据库和表
4.创建实体类
使用lombok插件:它可以帮你生成实体类的get和set方法 而且可以帮你生成构造方法。重写toString方法
(1)引入lombok jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
(2)创建实体类
@Data //getter,setter和toString
@NoArgsConstructor //无参构造
@AllArgsConstructor //所有有参构造
public class User {
private int id;
private String username;
private String name;
}
5.创建mybatis和数据库的映射文件 (在resources中创建目录mapper。并在mapper中创建User Mappe.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">
<!--namespace:命名空间
可以随便起名,但是后期我们要求命名空间的值必须和所对应的dao相同
-->
<mapper namespace="com.tym">
<!--
id:标签的唯一标识
resultType: 定义返回的类型 把sql查询的结果封装到哪个实体类钟
parametertype: 参数类型
#{必须和属性对应}
#{id}===表示占位符等价于? 这是mybatis框架的语法
-->
<select id="userIdFind" resultType="com.tym.entity.User">
select * from t_user where id=#{id}
</select>
<insert id="userInsert" parameterType="com.tym.entity.User">
insert into t_user values(null,#{username},#{name})
</insert>
<delete id="userDelete" parameterType="int">
delete from t_user where id=#{id}
</delete>
<select id="userFindAll" resultType="com.tym.entity.User">
select * from t_user
</select>
<update id="userUpdate" parameterType="com.tym.entity.User">
update t_user set username=#{username},name=#{name} where id=#{id}
</update>
</mapper>
注意:==把映射文件注册到配置文件上== mybatis.xml上
6.测试mydatis
public class Test02 {
@Test//测试根据id查询
public void testIdFiind()throws Exception{
//1.读取mybatis配置文件的内容----未来不需要写tomcat 解析配置文件
Reader reader= Resources.getResourceAsReader("mybatis.xml");
//2. 获取SqlSessionFactory对象
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
//3. 获取SqlSession对象----封装了对数据库操作的各种方法
SqlSession session = factory.openSession();
//调用查询一个结果的接口
//String statement, 命名空间+id----指向sql标签
// Object parameter 需要实参
User user = session.selectOne("com.tym.userIdFind", 1);
System.out.println(user);
session.close();
}
@Test//测试添加
public void testAdd()throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
User user = new User();
user.setUsername("xy");
user.setName("XY");
int row = session.insert("com.tym.userInsert", user);
System.out.println(row);
session.commit();
session.close();
}
@Test//测试删除
public void testDelete()throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
int insert = session.delete("com.tym.userDelete", 5);
System.out.println(insert);
session.commit();
session.close();
}@Test//测试查询所有
public void testFindAll()throws Exception{
Reader reader =Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
List<Object> list = session.selectList("com.tym.userFindAll");
System.out.println(list);
session.commit();
session.close();
}
@Test//测试修改
public void testUpdate()throws Exception{
Reader reader =Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
User user = new User(7,"xzq","薛之谦");
int row = session.update("com.tym.userUpdate", user);
System.out.println(row);
session.commit();
session.close();
}
}
三.mydatis的一些优化
1.为实体类起别名(在mybatis.xml配置文件 )
<typeAliases>
<!--单独为某个实体类起别名 -->
<typeAlias type="com.ykq.entity.User" alias="u"/>
<!--为指定包下的实体类起别名该别名就是实体类名-->
<package name="com.ykq.entity"/>
</typeAliases>
2.添加sql日志
(1)引入log4j的jar包
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
(2) 添加日志的文件配置(在resources中创建)--log4j.properties必须
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG