第一步:创建普通的java工程
第二步:加入jar包
各jar包作用
asm-3.3.1.jar结合cglib-2.2.2.jar用于生成动态代理类
commons-loggin-1.1.1.jar是apache开发出来用来兼容java.util.logging和log.4j的包
log.4j三个jar包用于支持log4j日志运行
mybatis-3.2.7.jar是mybatis的核心运行包
mysql数据库驱动包
slf4j-api本质是一个接口定义,是众多接口的集合,它不负责日志的实现,slf4j-log4j链接slf4j-api和log4j中间的适配器
第三步:在classpath下创建log4j.properties文件
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# 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
第四步:在classpath下创建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>
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC" />
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
第五步:创建po类,po类是用于作为mybatis进行sql映射使用,通常与数据库表对应
public class User {
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
第六步:在classpath下的sqlmap目录下创建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">
</mapper>
第七步:在SqlMapConfig.xml配置文件中加载User.xml配置文件
<mappers>
<!-- resource基于classpath查找 -->
<mapper resource="sqlmap/user.xml"/>
</mappers>
以上就将mybatis的基本配置完成了,下面根据需求来补充代码,实现可以通过mybatis访问数据库的操作
由于并没有整合spring等其他框架,项目也并非web项目,所以使用junit单元测试来完成测试!
public class MyFirstMybatis {
//会话工厂
private SqlSessionFactory sqlSessionFactory = null;
/**
* 每次启动之前先执行,获取一个sqlSessionFactory会话工厂
* @throws IOException
*/
@Before
public void createSqlSessionFactory() throws IOException{
// 配置文件
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
/**
* // 根据 id查询用户信息
*/
@Test
public void testFindUserById(){
//数据库会话实例
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
// 查询单个记录,根据用户id查询用户信息
User user = sqlSession.selectOne("test.findUserById",10);
// 输出用户信息
System.out.println(user.getId()+"---"+user.getUsername()+"---"+user.getBirthday()+"---"+user.getSex()+"---"+user.getAddress());
} catch (Exception e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
}
}
/**
* 根据用户名查询用户信息(模糊查询)
*/
@Test
public void testFindUserByUsername(){
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
List<User> userList = sqlSession.selectList("test.findUserByUsername", "小");
for (User user : userList) {
System.out.println(user.getId()+"---"+user.getUsername()+"---"+user.getBirthday()+"---"+user.getSex()+"---"+user.getAddress());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
}
}
/**
* 添加用户
*/
@Test
public void testInsert(){
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
User user = new User();
// 添加用户信息
user.setUsername("小刚");
user.setSex("女");
user.setBirthday(new Date());
user.setAddress("顺义区");
sqlSession.insert("test.insertUser",user);
//提交事务
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
}
}
/**
* 删除用户
*/
@Test
public void testDelete() {
// 数据库会话实例
SqlSession sqlSession = null;
try {
// 创建数据库会话实例sqlSession
sqlSession = sqlSessionFactory.openSession();
// 删除用户
sqlSession.delete("test.deleteUserById",1);
// 提交事务
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
/**
* 更新用户信息
*/
@Test
public void testUpdate() {
// 数据库会话实例
SqlSession sqlSession = null;
try {
// 创建数据库会话实例sqlSession
sqlSession = sqlSessionFactory.openSession();
// 添加用户信息
User user = new User();
user.setId(0);
user.setUsername("张小明");
user.setAddress("河南郑州");
user.setBirthday(new Date());
user.setSex("男");
sqlSession.update("test.updateUser", user);
// 提交事务
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
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="com.jxliu.mybatis.po.User">
select * from User where id = #{id};
</select>
<select id="findUserByUsername" parameterType="string" resultType="com.jxliu.mybatis.po.User">
select * from User where username like "%${value}%"
</select>
<insert id="insertUser" parameterType="com.jxliu.mybatis.po.User">
<!-- selectKey将主键返回,需要再返回 -->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID();
</selectKey>
insert into User(id,username,sex,birthday,address) values (#{id},#{username},#{sex},#{birthday},#{address})
</insert>
<!-- 删除用户 -->
<delete id="deleteUserById" parameterType="int">
delete from user where id=#{id}
</delete>
<!-- 更新用户 -->
<update id="updateUser" parameterType="com.jxliu.mybatis.po.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
where id=#{id}
</update>
</mapper>