首页 > 其他 > 详细

MyBatis 【增删改查】

时间:2014-04-02 10:03:49      阅读:480      评论:0      收藏:0      [点我收藏+]

configuration.xml     , MyBatis主配置文件

bubuko.com,布布扣
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
 3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 
 5 <!-- 注意:每个标签必须按顺序写,会提示错误:-->
 6 <configuration>
 7     <!-- 属性配置 -->
 8     <properties resource="jdbc.properties"/>
 9     
10     <!-- 设置缓存和延迟加载等等重要的运行时的行为方式 -->
11     <settings>
12         <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间  -->
13         <setting name="defaultStatementTimeout" value="25000"/>
14     </settings>
15     
16     <!-- 别名 -->
17     <typeAliases>
18         <typeAlias alias="User" type="com.mybatis.model.User"/>
19     </typeAliases>
20     
21     <environments default="development">
22         <!-- environment 元素体中包含对事务管理和连接池的环境配置 -->
23         <environment id="development">
24             <transactionManager type="JDBC" />
25             <dataSource type="POOLED">
26                 <property name="driver" value="${driver}" />
27                 <property name="url" value="${url}" />
28                 <property name="username" value="${username}" />
29                 <property name="password" value="${password}" />
30             </dataSource>
31         </environment>
32     </environments>
33     
34     <!-- ORM映射文件 -->
35     <mappers>
36         <mapper resource="com/mybatis/model/UserSqlMap.xml" />
37     </mappers>
38 </configuration> 
bubuko.com,布布扣

 jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8
username=root
password=123456

 log4j.properties

bubuko.com,布布扣
log4j.rootLogger=debug, stdout, R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=firestorm.log

log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

log4j.logger.com.codefutures=DEBUG
bubuko.com,布布扣

 User .java

bubuko.com,布布扣
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;
    }

}
bubuko.com,布布扣

UserMap.xml

bubuko.com,布布扣
<?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>
bubuko.com,布布扣

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

bubuko.com,布布扣
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();
        }
    }
}
bubuko.com,布布扣

UserDao interface

bubuko.com,布布扣
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();
    
}
bubuko.com,布布扣

UserDaoImpl

bubuko.com,布布扣
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;
    }
    
}
bubuko.com,布布扣

测试类:

bubuko.com,布布扣
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);
    }

}
bubuko.com,布布扣

 

转自:http://qingling600.iteye.com/blog/1832858#

MyBatis 【增删改查】,布布扣,bubuko.com

MyBatis 【增删改查】

原文:http://www.cnblogs.com/luffya/p/3638206.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!