Mybatis 环境搭建
Mybatis简介:开源免费框架,原名iBatis。
-
数据访问层框架
-
底层是对JDBC的封装
一、mysql时区报错
-
show variables like '%time_zone';
-
set global time_zone='+8:00';
二、mybatis需要的jar包
-
mybatis.jar
-
mysql-connector-java.jar
三、src/mybaits.xml(配置数据库连接)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<configuration>
<environments default="default">
<environment id="default">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="test.xml"/>
</mappers>
</configuration>
四、test.xml(配置sql语句,理解成DAO的实现类)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<mapper namespace="a">
<select id="sel" resultType="a.b.T1">
select * from t1
</select>
</mapper>
五、Main.java
package a.b;
import java.io.IOException;
import java.io.InputStream;
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;
public class Main {
public static void main(String[] args) throws IOException {
InputStream is=Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory sf=new SqlSessionFactoryBuilder().build(is);
SqlSession ss=sf.openSession();
List<T1> list=ss.selectList("a.sel");
for(T1 data:list) {
System.out.println(data.toString());
}
ss.close();
}
}