标签:
1 . 定义 java实体类 User,建立user表 读者请自行完成准备工作。
User 类 有 id, name,age 属性
user 表 中 id,name,age字段 id自增长
2. 定义sql映射XML userMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE *** >
<!--
namespace 默认取 userMapper.xml的 全路径 + "." + 文件名去除后缀 即userMapper
-->
<mapper namespace ="com.atguigu.mybatis.userMapper">
<insert id="insertUser" parameterType="com.atguigu.ibatis.bean.User">
insert into users(name,age) values (#{name},#{age});
</insert>
<delete id="delUser" parameterType="int">
delete from users where id =#{id}
</delete>
<update id="updateUser" parameterType="com.atguigu.ibatis.bean.User">
update users set name=#{name}, age=#{age} where id=#{id}
</update>
<select id="selUser" parameterType ="int" resultType="com.atguigu.ibatis.bean.User">
select * from users where id=#{id}
</select>
<select id="getAllUsers" resultType="com.atguigu.ibatis.bean.User">
select * from users
</select>
</mapper>
3.定义数据源连接池 相关配置
注册相关xml文件
<?xm l version = "1.0" encoding ="UTF-8" ?>
<configuration>
<environments default ="development">
<environment id="development">
<transactionManager type="JDBC" />
<datasource type="POOLED" >
<property name="driverClass" value="" />
<property name="jdbcUrl" value="" />
<property name="user" value="" />
<property name="password" value="" />
</datasource>
</environment>
</environments>
</configuration>
//注册相关 mapper xml
<mappers>
<mapper resource = "com/atguigu/mybatis/userMapper.xml" /> //路径名
</mappers>
</xml>
4. 编写测试代码
@Test
public void testAdd(){
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession(); //默认手动提交事务
String statement = "com.atguigu.mybatis.userMapper.addUser"; //namespace+ "." + id
session.insert(statement,new User(-1,"kk",22);
session.commit(); //提交事务
session.close();
}
@Test
public void testDel(){
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession(); //默认手动提交事务
String statement = "com.atguigu.mybatis.userMapper.delUser";
session.insert(statement,2);
session.commit(); //提交事务
session.close();
}
@Test
public void testUpdate(){
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession(true); //设置自动提交
String statement = "com.atguigu.mybatis.userMapper.updateUser;
session.update(statement, new User(4,"kk4",333));
session.close();
}
public void testGetUser(){
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession();
String statement = "com.atguigu.mybatis.userMapper.selUser";
User user = session.selectOne(statement, 1);
session.close();
System.out.println(user);
}
@Test
public void getAllUsers(){
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession(true); //设置自动提交
String statement = "com.atguigu.mybatis.userMapper.getAllUsers";
List<User> users = session.selectList(statement);
session.close();
}
mybatis 快速入门
标签:
原文地址:http://www.cnblogs.com/xifenglou/p/5603387.html