| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
55bd
12年前发布

MyBatis3 之增删改查操作

MyBatis3  之  CRUD:

jar包就不上了,主要看代码。先总览一下文件结构:

MyBatis3 之增删改查操作

然后是代码:

1)configuration.xml     , MyBatis主配置文件

<?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>   <!-- 属性配置 -->   <properties resource="jdbc.properties"/>      <!-- 设置缓存和延迟加载等等重要的运行时的行为方式 -->   <settings>    <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间  -->    <setting name="defaultStatementTimeout" value="25000"/>   </settings>      <!-- 别名 -->   <typeAliases>    <typeAlias alias="User" type="com.mybatis.model.User"/>   </typeAliases>      <environments default="development">    <!-- environment 元素体中包含对事务管理和连接池的环境配置 -->    <environment id="development">     <transactionManager type="JDBC" />     <dataSource type="POOLED">      <property name="driver" value="${driver}" />      <property name="url" value="${url}" />      <property name="username" value="${username}" />      <property name="password" value="${password}" />     </dataSource>    </environment>   </environments>      <!-- ORM映射文件 -->   <mappers>    <mapper resource="com/mybatis/model/UserSqlMap.xml" />   </mappers>     </configuration> 

 2)jdbc.properties

driver=com.mysql.jdbc.Driver  url=jdbc:mysql://localhost:3306/mybatis  username=root  password=123456

3)log4j.properties

log4j.rootLogger=DEBUG,A1  # \u8f93\u51fa\u5230\u63a7\u5236\u53f0   log4j.appender.A1=org.apache.log4j.ConsoleAppender   log4j.appender.A1.layout=org.apache.log4j.PatternLayout   log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [\u65E5\u5FD7\u4FE1\u606F] %m%n

4)User .java

package com.mybatis.model;    import java.io.Serializable;    @SuppressWarnings("serial")  public class User implements Serializable {      private int id;   private String userName;   private String password;      public User(){   }      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 getPassword() {    return password;   }   public void setPassword(String password) {    this.password = password;   }    }

5)UserSqlMap.xml

<?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE mapper       PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"       "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">            <!-- namespace用于java代码调用时识别指定xml的mapper文件 -->  <mapper namespace="com.mybatis.model.User">   <!-- 配置ORM映射 -->   <resultMap type="User" id="user_orm">    <id property="id" column="id"/>    <result property="userName" column="userName"/>    <result property="password" column="password"/>   </resultMap>      <!-- 用来定义可重用的SQL代码段 -->   <sql id="demo_sql">         userName,password   </sql>      <insert id="inser_user" parameterType="User">    <!-- include 引用可重用的SQL代码段 -->    INSERT INTO USER(<include refid="demo_sql"/>) VALUES(#{userName},#{password})   </insert>      <update id="update_user" parameterType="User">    UPDATE USER SET userName=#{userName} ,password=#{password}  WHERE id=#{id}   </update>      <update id="delete_user" parameterType="int">    DELETE FROM USER WHERE id=#{id}   </update>          <select id="selectAll_user" useCache="false" flushCache="true" resultMap="user_orm">       SELECT * FROM USER     </select>          <!-- 使用map传人多个参数 -->      <select id="selectList_user" useCache="false" flushCache="true" parameterType="map" resultMap="user_orm">       SELECT * FROM USER LIMIT #{pageNow},#{pageSize}      </select>          <select id="selectById_user" parameterType="int" resultType="User">       SELECT * FROM USER WHERE id= #{id}     </select>          <select id="selectCount_user"  resultType="int">       SELECT count(*) FROM USER      </select>          <select id="selectByName_user" parameterType="String" resultType="User">       SELECT * FROM USER WHERE userName= #{userName}     </select>       </mapper>  

6)SessionFactoryUtil.java  MyBatis工具类,用于创建SqlSessionFactory

package com.mybatis.sessionfactory;    import java.io.IOException;  import java.io.Reader;    import org.apache.ibatis.io.Resources;  import org.apache.ibatis.session.SqlSession;  import org.apache.ibatis.session.SqlSessionFactory;  import org.apache.ibatis.session.SqlSessionFactoryBuilder;    public class SessionFactoryUtil {      private static final String RESOURCE = "Configuration.xml";   private static SqlSessionFactory sqlSessionFactory = null;   private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();     static {    Reader reader = null;    try {     reader = Resources.getResourceAsReader(RESOURCE);    } catch (IOException e) {     throw new RuntimeException("Get resource error:"+RESOURCE, e);    }      sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);   }      /**    * Function  : 获得SqlSessionFactory    */   public static SqlSessionFactory getSqlSessionFactory(){             return sqlSessionFactory;         }      /**    * Function  : 重新创建SqlSessionFactory    */   public static void rebuildSqlSessionFactory(){    Reader reader = null;    try {     reader = Resources.getResourceAsReader(RESOURCE);    } catch (IOException e) {     throw new RuntimeException("Get resource error:"+RESOURCE, e);    }      sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);   }      /**    * Function  : 获取sqlSession    */   public static SqlSession getSession(){    SqlSession session = threadLocal.get();        if(session!=null){     if(sqlSessionFactory == null){      getSqlSessionFactory();     }     //如果sqlSessionFactory不为空则获取sqlSession,否则返回null     session = (sqlSessionFactory!=null) ? sqlSessionFactory.openSession(): null;    }        return session;   }      /**    * Function  : 关闭sqlSession    */   public static void closeSession(){    SqlSession session = threadLocal.get();    threadLocal.set(null);    if(session!=null){     session.close();    }   }  }

7)UserDao interface

package com.mybatis.dao;    import java.util.List;    import com.mybatis.model.User;    public interface UserDao {      public User load(int id);   public void add(User user);   public void update(User user);   public void delete(int id);   public User findByName(String userName);   public List<User>  queryAllUser();   public List<User> list(int pageNow,int pageSize);   public int getAllCount();     }

8)UserDaoImpl

package com.mybatis.dao.implment;    import java.util.HashMap;  import java.util.List;  import java.util.Map;    import org.apache.ibatis.session.SqlSession;    import com.mybatis.dao.UserDao;  import com.mybatis.model.User;  import com.mybatis.sessionfactory.SessionFactoryUtil;      public class UserDaoImpl implements UserDao {      public User load(int id){    SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();    User user = (User) session.selectOne("com.mybatis.model.User.selectById_user", id);    session.close();    return user;   }     public void add(User user) {    SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();    session.insert("com.mybatis.model.User.inser_user", user);    session.commit();    session.close();   }      public void update(User user){    SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();    session.update("com.mybatis.model.User.update_user", user);    session.commit();    session.close();   }      public void delete(int id){    SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();    session.delete("com.mybatis.model.User.delete_user", id);    session.close();   }      public User findByName(String userName){    SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();    User user = (User)session.selectOne("com.mybatis.model.User.selectByName_user", userName);    session.close();    return user;   }      @SuppressWarnings("unchecked")   public List<User> queryAllUser() {    SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();    List<User> list = session.selectList("com.mybatis.model.User.selectAll_user");    session.close();    return list;   }      @SuppressWarnings("unchecked")   public List<User> list(int pageNow , int pageSize){    SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();    Map<String,Object> params = new HashMap<String ,Object>();    params.put("pageNow", pageNow);    params.put("pageSize", pageSize);    List<User> list = session.selectList("com.mybatis.model.User.selectList_user", params);    session.close();    return list;   }      public int getAllCount(){    SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();    int count = (Integer) session.selectOne("com.mybatis.model.User.selectCount_user");    session.close();    return count;   }     }

9)测试类:

package com.mybatis.dao.implment;    import java.util.List;    import org.junit.Test;    import com.mybatis.dao.UserDao;  import com.mybatis.model.User;    public class UserDaoTest {      private UserDao userDao = new UserDaoImpl();      @Test   public void testLoad(){    User u = userDao.load(1);    if(u!=null){     System.out.println("UserId:"+u.getId()+"  UserName:"+u.getUserName()+"  Password:"+u.getPassword());    }    else{     System.out.println("id不存在!!");    }   }      @Test   public void testAdd(){    User user = new User();    user.setUserName("admin5");    user.setPassword("123456");    userDao.add(user);   }      @Test   public void testUpdate(){    User user = new User();    user.setId(2);    user.setUserName("manager");    user.setPassword("123456");    userDao.update(user);   }      @Test   public void testQueryAllUser(){    List<User> list = userDao.queryAllUser();    if(list!=null&list.size()>0){     for(User u:list){      System.out.println("UserId:"+u.getId()+"  UserName:"+u.getUserName()+"  Password:"+u.getPassword());     }    }   }      @Test   public void testFindByName(){    User u = userDao.findByName("admin");    if(u!=null){     System.out.println("UserId:"+u.getId()+"  UserName:"+u.getUserName()+"  Password:"+u.getPassword());    }    else{     System.out.println("用户名不存在!!");    }   }      @Test   public void testList(){    List<User> list = userDao.list(1, 4);    if(list!=null&list.size()>0){     for(User u:list){      System.out.println("UserId:"+u.getId()+"  UserName:"+u.getUserName()+"  Password:"+u.getPassword());     }    }   }      @Test   public void testGetAllCount(){     System.out.println("All Count : "+userDao.getAllCount());   }      @Test   public void testDelete(){    userDao.delete(3);   }    }

10)执行testFindByName():

MyBatis3 之增删改查操作

 

 

 本文由用户 55bd 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1349622424072.html
MyBatis3 持久层框架