概念:
- mybatis是一个持久层的框架,是apache下的*项目
- 让程序将主要精力放在sql上,通过mybatis提供的映射方式,*灵活生成需要的sql语句。
- 可以将向
prepareStatement
中的参数自动进行输入映射,将查询结果集灵活映射成java对象。(输出映射)
遇见的问题:
①Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is
com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
原因:使用了当前最新的mysql-connector-java-8.0.11-.jar
的MySQL驱动包,新的驱动包中`com.mysql.jdbc.Driver'类已经过时,它通过SPI自动注册,不再需要手动加载驱动类
②java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone.
修改方法:value="jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8"/
③当数据表中的内容为Date类型时,查询语句会报错。不知原因,有大佬知道的话请告诉一下
体系结构
导入所需jar包:
根据Id查询数据
- log4j.properties
log4j.rootLogger = DEBUG,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
- User.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="test">
<select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.Employee">//parameterType输入类型,resultType输出结果类型
select id,username,sex,address from users where id=#{id};//#{}是一个占位符
</select>
</mapper>
- SqlMapConfig.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"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>
</configuration>
- Employee.java
package cn.itcast.mybatis.po;
import java.sql.Date;
public class Employee {
private int id;
private String username;
private String sex;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Employee [id=" + id + ", username=" + username + ", sex=" + sex + ", address=" + address + "]";
}
}
- MybatisFirst.java
package sqlmap;
import java.io.IOException;
import java.io.InputStream;
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 cn.itcast.mybatis.po.Employee;
public class MybatisFirst {
@Test
public void findUserByIdTest() throws IOException{
String resource="SqlMapConfig.xml";//配置文件
InputStream inputStream= Resources.getResourceAsStream(resource);//得到配置文件流
SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);//创建会话工厂,传入配置文件信息
SqlSession sqlSession =sqlSessionFactory.openSession();//通过工厂得到sqlsession
Employee employee =sqlSession.selectOne("test.findUserById",1);//是selectOne查询一条数据
System.out.println(employee);
sqlSession.close(); //关闭会话
}
}
根据名称模糊查询数据
- SqlMapConfig.xml
<select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.Employee">
select id,username,sex,address from users where username like '%${value}%';//${}可能会引起sql注入,只是一个拼接符,不做任何改变
</select>
- 测试文件
@Test
public void findUserByNameTest() throws IOException{
String resource="SqlMapConfig.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession =sqlSessionFactory.openSession();
java.util.List<Employee> list= sqlSession.selectList("test.findUserByName", "zhao");//selectList查询多条数据
System.out.println(list);
sqlSession.close();
}
向数据库中添加数据
- SqlMapConfig.xml
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.Employee">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID(); //查询自增的主键值
</selectKey>
insert into users(id,username,sex,address)value(#{id},#{username},#{sex},#{address});
</insert>
- 测试文件
@Test
public void insertUserTest() throws IOException{
String resource="SqlMapConfig.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession =sqlSessionFactory.openSession();
Employee employee= new Employee();
employee.setId(10);
employee.setUsername("wu");
employee.setSex("nv");
employee.setAddress("henan");
sqlSession.insert("test.insertUser",employee);
sqlSession.commit();
System.out.println(employee.getId());//输出自增的主键值
sqlSession.close();
}
从数据库中删除文件
- SqlMapConfig.xml
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from users where id=#{id};
</delete>
- 测试文件
@Test
public void deleteUserTest() throws IOException{
String resource="SqlMapConfig.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession =sqlSessionFactory.openSession();
sqlSession.delete("test.deleteUser",12);
sqlSession.commit();
sqlSession.close();
}
更新数据库中的数据
- SqlMapConfig.xml
<update id="updateUser" parameterType="cn.itcast.mybatis.po.Employee">
update users set username=#{username},sex=#{sex},address=#{address} where id=#{id};
</update>
- 测试文件
@Test
public void updateUserTest() throws IOException{
String resource="SqlMapConfig.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession =sqlSessionFactory.openSession();
Employee employee= new Employee();
employee.setId(13);
employee.setUsername("sheng");
employee.setSex("nv");
employee.setAddress("diqiu");
sqlSession.update("test.updateUser",employee);
sqlSession.commit();
sqlSession.close();
}