1.核心配置
文件:mybatis-config.xml
<!-- 映射文件的配置-->
<mappers>
<!--一般不使用这种方式-->
<!--<mapper resource="mapper/UserMapper.xml"/>-->
<!--<mapper class="mapper.UserMapper"></mapper>-->
<package name="mapper"></package>
</mappers>
2.映射配置
文件:UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
select * from t_user
<select id="selectById" resultType="com.yunhe.poio.User">
select * from t_user where id= #{id}
</select>
<!--
<insert id=""></insert>
<delete id=""></delete>
<update id=""></update>
-->
</mapper>
3.log4j.properties配置文件
Global logging configuration
log4j.rootLogger=DEBUG, stdout
MyBatis logging configuration…
log4j.logger.org.mybatis.example.BlogMapper=TRACE
Console output…
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4.读取文件(sqlSessionFactory恶汉模式)
//静态恶汉单例模式
private MyBatisUitl(){}
private static SqlSessionFactory sqlSessionFactory;
static{
try {
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsStream(“mybatis-config.xml”));
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
5.使用工厂类
//1、创建SqlSessionFactory对象,也是单例模式的
SqlSessionFactory factory = MyBatisUitl.getSqlSessionFactory();
//2、创建SqlSession对象
SqlSession session = factory.openSession();
//3、调用session的方法namespace的名字.id
//如果核心配置文件不使用package的情况下用下面两种
// List users = session.selectList(“user.selectAllUser”);
//User user = session.selectOne(“user.selectById”, 2 );
//System.out.println(user);
//如果配置文件读取一个包的的mapper.xml情况下使用
UserMapper mapper = session.getMapper(UserMapper.class);
mapper.selectAllUser();
//5、关闭资源
session.close();
5.maven工程的pro文件要加上xml解析器
<–mybatis jar包–>
org.mybatis
mybatis
3.4.5
<–mysql jar包–>
mysql
mysql-connector-java
5.1.32
<–实体类自动生成器 jar包–>
org.projectlombok
lombok
1.18.6
provided