学习大神笔记之“MyBatis学习总结(二)”

MyBatis对表的增删改查操作

        主要有两种方式:基于XML实现和基于注解实现。

完整项目结构:

学习大神笔记之“MyBatis学习总结(二)”

工具类:MyBatisUtil-------用于获取  sqlsession

 package me.gacl.test;

 import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { /**
* 获取SqlSessionFactory
* @return SqlSessionFactory
*/ public static SqlSessionFactory getSqlSessionFactory(){
String resource = "conf.xml";
InputStream is = MyBatisUtil.class.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
return factory;
} /**
* 获取SqlSession
* @return SqlSesstion
* @throws
*/
public static SqlSession getSqlSession(){
return getSqlSessionFactory().openSession();
} /**
* 获取SqlSession
* @param isAutoCommit
* true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
* false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
* @return SqlSession
*/
public static SqlSession getSqlSession(boolean isAutoCommit){
return getSqlSessionFactory().openSession(isAutoCommit);
}
}

  一、基于XML实现:(新建方法)

          思路总结:

在 userMapper.xml 文件中进行增删改查实现,

在测试类中映射xml文件中的sql(包名.文件名前缀.方法id): String statement = "me.gacl.mapping.userMapper.addUser";

当新增成功,返回的retResult为1:int retResult = sqlSession.insert(statement,user);

代码实现:

           conf.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="liyangkun123" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource = "me/gacl/mapping/userMapper.xml" ></mapper>
</mappers> </configuration>

         数据库驱动:<property name="driver" value="com.mysql.jdbc.Driver" />       

         <mapper   />==<mapper></mapper>

        userMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)--> <mapper namespace="me.gacl.mapping.userMapper"> <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复使用parameterType属性指明查询时
使用的参数类型,resultType属性指明查询返回的结果集类型resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回
User类就是users表所对应的实体类--> <!-- 根据id查询得到一个user对象 -->
<select id="getUser" parameterType="int" resultType="me.gacl.domain.User">
select * from users where id=#{id}
</select> <!-- 新增用户(Create) -->
<insert id="addUser" parameterType="me.gacl.domain.User">
insert into users(name,age)values(#{name},#{age})
</insert> <!-- 修改用户(Update) -->
<update id="updateUser" parameterType="me.gacl.domain.User">
update users set name=#{name},age=#{age} where id=#{id}
</update> <!-- 删除用户(Delete) -->
<delete id="deleteUser" parameterType="int">
delete from users where id=#{id}
</delete> <!-- 查询所有用户 -->
<select id="getAllUsers" resultType="me.gacl.domain.User">
insert * from users
</select> </mapper>

           测试类:TestCRUDByXmlMapper----单元测试验证

 package me.gacl.test;

 import org.apache.ibatis.session.SqlSession;
import org.junit.Test; import me.gacl.domain.User; public class TestCRUDByXmlMapper { @Test
public void testAdd(){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
String statement = "me.gacl.mapping.userMapper.addUser";
User user = new User();
user.setName("用户孤傲苍狼");
user.setAge(20); int retResult = sqlSession.insert(statement, user);
sqlSession.close();
System.out.println(retResult);
} @Test
public void testUpdate(){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
String statement = "me.gacl.mapping.userMapper.updateUser";
User user = new User();
user.setId(2);
user.setName("zhu");
user.setAge(25); int retResult = sqlSession.update(statement, user);
sqlSession.close();
System.out.println(retResult);
} @Test
public void testdeleteUser(){
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
String statement = "me.gacl.mapping.userMapper.deleteUser"; int retResult =sqlSession.delete(statement,1);
sqlSession.close();
System.out.println(retResult);
}
}

SqlSession sqlSession = MyBatisUtil.getSqlSession(true);//获取session(内有链接数据库的配置),连上数据库,才能进行操作。

   二、基于注解实现:(新建方法)

写一个接口类定义sql映射,并且我们不用写接口实现,而是由MyBatis动态构建,我们只需要直接拿来使用即可。

接下来将接口类注册到配置文件中(conf.xml) :

借鉴大神代码:

<!-- 注册UserMapper映射接口-->
          <mapper class="me.gacl.mapping.UserMapperI"/>

下一步测试类测试:

注意在新增之前要获得 sqlsession并且open,操作之后要close。

创建接口实例,

获取操作对象,修改操作信息

然后调用增删改查方法执行(借用大神代码)

代码实现:

         UserMapper.java----增删改查接口

 package me.gacl.mapping;

 import java.util.List;

 import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import me.gacl.domain.User; public interface UserMapperI { @Insert("insert into users(name,age) value(#{name},#{age})")
public int add(User user); @Delete("delete from users where id=#{id}")
public int deleteById(int id); @Select("select * from users where id=#{id}")
public User selectById(int id); @Update("update users set name=#{name},age=#{age} where id=#{id}")
public int updateById(User user); @Select("select * from users")
public List<User> getAll();
}

         注册到conf.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>
<!-- 引用db.properties配置文件 -->
<properties resource="me/gacl/test/db.properties" /> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="liyangkun123" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource = "me/gacl/mapping/userMapper.xml" ></mapper>
<mapper class="me.gacl.mapping.UserMapperI" />
</mappers> </configuration>

         resource和class为包+名完整路径          

        TestCRUDByAnnotationMapper.java------测试类

 package me.gacl.test;

 import java.util.List;

 import org.apache.ibatis.session.SqlSession;
import org.junit.Test; import me.gacl.domain.User;
import me.gacl.mapping.UserMapperI;
import me.gacl.test.MyBatisUtil; public class TestCRUDByAnnotationMapper { @Test
public void testAdd(){
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
User user = new User();
user.setName("用户xdp");
user.setAge(29);
int add = mapper.add(user); sqlSession.close();
System.out.println(add);
} @Test
public void testDelete(){
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
int delete = mapper.deleteById(1);
sqlSession.close();
System.out.println(delete);
} @Test
public void testUpdate(){
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
User user = new User();
user.setId(2);
user.setName("Linda");
user.setAge(23); int update = mapper.updateById(user);
sqlSession.close();
System.out.println(update);
} @Test
public void testSelect(){
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
User user = mapper.selectById(2);
sqlSession.close();
System.out.println(user); } @Test
public void testSelectAll(){
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
List<User> user = mapper.getAll(); sqlSession.close();
System.out.println(user); }
}

注意事项:MyBatisUtil.java,conf.xml, 放到 util 包中时,调用出错,放到同一个包中,没有问题。

大神总结链接:http://www.cnblogs.com/xdp-gacl/p/4262895.html

上一篇:React.js终探(五)


下一篇:React.js再探(三)