下面举个例子:
1.首先来配置一下log4j.properties日志信息文件
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.mybatis.mapper=DEBUG
# 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
2.在持久层po包中创建MyUser持久化类
package mybatis.po;
public class MyUser {
private Integer uid;//主键
private String uname;
private String usex;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUsex() {
return usex;
}
public void setUsex(String usex) {
this.usex = usex;
}
@Override
public String toString() {//为了方便查看结果,重写了toString方法
return "User [uid=" + uid +",uname=" + uname + ",usex=" + usex +"]";
}
}
3.创建核心配置文件mybatis-config.xml
4.在映射层mapper包创建UserMapper.xml文件
insert into user (uname,usex) values(#{uname},#{usex})
update user set uname = #{uname},usex = #{usex} where uid = #{uid}
delete from user where uid = #{uid}
5.在测试test包创建MyBatisTest类
package mybatis.test;
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;
import mybatis.po.MyUser;
public class MyBatisTest {
public static void main(String[] args) {
try {
//读取配置文件mybatis-config.xml
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
//根据配置文件构建SqlSessionFactory(会话工厂)
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
//通过SqlSessionFactory创建SqlSession(会话)
SqlSession ss = ssf.openSession();
//查询一个用户
MyUser mu = ss.selectOne("mybatis.mapper.UserMapper.selectUserById", 1);
System.out.println("查询到用户:" + mu);
//测试一级缓存
mu = ss.selectOne("mybatis.mapper.UserMapper.selectUserById", 1);
System.out.println("测试一级缓存:" + mu);
//添加一个用户
MyUser addmu = new MyUser();
addmu.setUname("陈恒");
addmu.setUsex("男");
ss.insert("mybatis.mapper.UserMapper.addUser", addmu);
System.out.println("添加用户成功。");
//修改一个用户
MyUser updatemu = new MyUser();
updatemu.setUid(2);
updatemu.setUname("张三");
updatemu.setUsex("女");
ss.update("mybatis.mapper.UserMapper.updateUser", updatemu);
System.out.println("修改用户成功。");
//删除一个用户
//ss.delete("com.mybatis.mapper.UserMapper.deleteUser", 2);
//测试一级缓存
mu = ss.selectOne("mybatis.mapper.UserMapper.selectUserById", 1);
System.out.println("测试一级缓存:" + mu);
//查询所有用户
List listMu = ss.selectList("mybatis.mapper.UserMapper.selectAllUser");
System.out.println("查询所有用户:");
for (MyUser myUser : listMu) {
System.out.println(myUser);
}
//提交事务
ss.commit();
//关闭SqlSession
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)