首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

MyBatis3 之增删节查操作

2013-03-27 
MyBatis3 之增删改查操作?xml version1.0 encodingUTF-8?!DOCTYPE configuration PUBLIC -//myb

MyBatis3 之增删改查操作
<?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>

?jdbc.properties

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8username=rootpassword=123456

?log4j.properties

log4j.rootLogger=debug, stdout, Rlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p - %m%nlog4j.appender.R=org.apache.log4j.RollingFileAppenderlog4j.appender.R.File=firestorm.loglog4j.appender.R.MaxFileSize=100KBlog4j.appender.R.MaxBackupIndex=1log4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%p %t %c - %m%nlog4j.logger.com.codefutures=DEBUG

?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;}}

?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>    <!--模糊 MyIbatis 3.2.0-->    <select id="selectUserByName" parameterType="String" resultMap="user_orm">     SELECT * FROM USER WHERE userName like "%"#{userName}"%"</select>  </mapper>

? 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,否则返回nullsession = (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();}}}

?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();}

?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;}}

?测试类:

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();@Testpublic 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不存在!!");}}@Testpublic void testAdd(){User user = new User();user.setUserName("admin5");user.setPassword("123456");userDao.add(user);}@Testpublic void testUpdate(){User user = new User();user.setId(2);user.setUserName("manager");user.setPassword("123456");userDao.update(user);}@Testpublic 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());}}}@Testpublic 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("用户名不存在!!");}}@Testpublic 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());}}}@Testpublic void testGetAllCount(){System.out.println("All Count : "+userDao.getAllCount());}@Testpublic void testDelete(){userDao.delete(3);}}

?

热点排行