MyBatis (一)

一,测试项目结构图

MyBatis (一)


二,数据库、表的建立

#sequence
create sequence s_user minvalue 1 start with 1 increment by 1 nocache;

#table
create table t_user(
id int,
userName varchar2(30) constraint u_user_userName unique,
password varchar2(80),
description varchar2(250),
constraint p_user_id primary key(id)
);

#trigger 设置初始密码以及id自增
create or replace trigger tr_user
before insert
on t_user
for each row
declare
nextid int;
pwd varchar2(80) default 'happymzw';
begin
if :new.id is null or :new.id=0 then
select s_user.nextval
into nextid
from dual;
:new.id:=nextid;
end if;
if :new.password is null then
:new.password:=pwd;
end if;
end tr_user;


三,JAVA代码

1,db.properties

# db config
db.driver=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@localhost:1521:orcl
db.username=happymzw
db.password=happymzw

2,MyBatis-Configuration.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>

    <properties resource="db.properties" />
    
    <settings>
        <!-- 处理传入参数为空 -->
        <setting name="jdbcTypeForNull" value="NULL"/>
    </settings>
    
    <typeAliases>
        <package name="org.happymzw.pojo"/>  
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/happymzw/mapper/UserMapper.xml"/>
    </mappers>
    
</configuration>

3,org.happymzw.pojo.User

package org.happymzw.pojo;


/**
 * @author victor.min
 *
 */
public class User{

    private int id;
    private String userName;
    private String password;
    private String description;

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(final int id) {
        this.id = id;
    }
    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }
    /**
     * @param userName the userName to set
     */
    public void setUserName(final String userName) {
        this.userName = userName;
    }
    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }
    /**
     * @param password the password to set
     */
    public void setPassword(final String password) {
        this.password = password;
    }
    /**
     * @return the description
     */
    public String getDescription() {
        return description;
    }
    /**
     * @param description the description to set
     */
    public void setDescription(final String description) {
        this.description = description;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("User [id=");
        builder.append(id);
        builder.append(", userName=");
        builder.append(userName);
        builder.append(", password=");
        builder.append(password);
        builder.append(", description=");
        builder.append(description);
        builder.append("]");
        return builder.toString();
    }
}

4,org.happymzw.dao.UserDao

package org.happymzw.dao;

import java.util.List;

import org.happymzw.pojo.User;


/**
 * @author victor.min
 *
 */
public interface UserDao{

    public int insert(User user);

    public int delete(String userName);

    public int update(User user);

    public List<User> selectAll();

    public int countAll();

    public User findByUserName(String userName);


}

5,org.happymw.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="org.happymzw.dao.UserDao">

    <insert id="insert" parameterType="User">
        insert into t_user values(#{id}, #{userName}, #{password}, #{description})
    </insert>
    
    <delete id="delete" parameterType="String" >
        delete from t_user where userName=#{userName}
    </delete>
    
    <update id="update" parameterType="User">
        update t_user set userName=#{userName},password=#{password},description=#{description} where id=#{id}
    </update>
    
    <select id="countAll" resultType="int">
        select count(1) from t_user
    </select>
    
    <select id="selectAll" resultType="User">
        select * from t_user
    </select>
    
    <select id="findByUserName" parameterType="String" resultType="User">
        select * from t_user where userName=#{userName}
    </select>
</mapper>

6,org.happymzw.test.UserDaoTest

package org.happymzw.test;

import java.io.Reader;
import java.util.Iterator;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.happymzw.dao.UserDao;
import org.happymzw.pojo.User;
import org.junit.Test;

/**
 * @author victor.min
 *
 */
public class UserDaoTest {
    @Test
    public void userDaoTest() throws Exception {

        final String resource = "MyBatis-Configuration.xml";
        final Reader reader = Resources.getResourceAsReader(resource);
        final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        final SqlSessionFactory factory = builder.build(reader);

        final SqlSession session = factory.openSession();
        final UserDao userDao = session.getMapper(UserDao.class);

//        final User user = new User();
//        user.setId(7);
//        user.setUserName("happymzw2");
//        user.setPassword("123456");
//        user.setDescription("备注");
//
//        userDao.insert(user);
//        System.out.println("记录条数:"+userDao.countAll());


//        user.setDescription("Description");
//        userDao.update(user);
//        final User u1 = userDao.findByUserName("happymzw2");
//        System.out.println(u1.toString());

        userDao.delete("happymzw2");

        System.out.println("记录条数:"+userDao.countAll());
        final List<User> users = userDao.selectAll();
        final Iterator<User> iter = users.iterator();
        while(iter.hasNext()){
            final User u = iter.next();
            System.out.println("ID: " + u.getId()
                    + ", 用户名:" + u.getUserName()
                    + ", 密码:" + u.getPassword()
                    + ", 备注: " + u.getDescription());
        }

        session.commit();
        session.close();
    }
}


四,后记

more information about mybatis : http://mybatis.github.io/mybatis-3/index.html


你可能感兴趣的:(mybatis)