关闭

MyBatis(2)--MyBatis标准示例(单例)

标签: mybatisjava
118人阅读 评论(0) 收藏 举报
分类:

标准示例

1. 项目结构目录

 项目结构目录


2. 源码

1>.log4j.properties

log4j.rootLogger=DEBUG , stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

2>.Role.java

package com.anlw.model;

public class Role {
    private Long id;
    private String roleName;
    private String note;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    @Override
    public String toString() {
        return "Role [id=" + id + ", roleName=" + roleName + ", note=" + note + "]";
    }
}

3>.RoleMapper.java

package com.anlw.mapper;

import com.anlw.model.Role;

public interface RoleMapper {

    Role getRole(Long id);

    void insertRole(Role role);

    void deleteRole(Long id);

}

4>.roleMapper.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="com.anlw.mapper.RoleMapper">
    <select id="getRole" resultType="role" parameterType="long">
        select id,role_name as roleName,note from t_role where id = #{id}
    </select>
    <insert id="insertRole" parameterType="role">
        insert into t_role(role_name,note) values (#{roleName},#{note})
    </insert>
    <delete id="deleteRole" parameterType="long">
        delete from t_role where id = #{id}
    </delete>
</mapper>

5>.mybatis-config.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>
    <typeAliases>
        <typeAlias type="com.anlw.model.Role" alias="role" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="autoCommit" value="true"/>
            </transactionManager>
            <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="123456" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="roleMapper.xml" />
    </mappers>
</configuration>

6>.SqlSessionFactoryUtil.java

package com.anlw.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

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 SqlSessionFactoryUtil {
    // SqlSessionFactory对象
    private static SqlSessionFactory  sqlSessionFactory = null;
    //类线程锁
    private  static final Class<SqlSessionFactoryUtil> CLASS_LOCK = SqlSessionFactoryUtil.class;
    //私有化构造器
    private SqlSessionFactoryUtil(){}

    //构建SessionFactory
    public static SqlSessionFactory initSqlSessionFactory(){
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            Logger.getLogger(SqlSessionFactory.class.getName()).log(Level.SEVERE, null, e);
        }
        synchronized (CLASS_LOCK) {
            if(sqlSessionFactory == null){
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }
        }
        return sqlSessionFactory;
    }

    //打开SqlSession
    public static SqlSession openSqlSession(){
        if(sqlSessionFactory == null){
            initSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }
}

7>.Test.java

package com.anlw.main;

import org.apache.ibatis.session.SqlSession;

import com.anlw.mapper.RoleMapper;
import com.anlw.model.Role;
import com.anlw.util.SqlSessionFactoryUtil;

public class Test {
    public static void main(String[] args) {
        SqlSession session = null;
        try {
            session = SqlSessionFactoryUtil.openSqlSession();
            RoleMapper roleMapper = session.getMapper(RoleMapper.class);
            Role role = new Role();
            role.setRoleName("test");
            role.setNote("0825s");
            //insert
            roleMapper.insertRole(role);
            //delete
            roleMapper.deleteRole(3L);
            session.commit();
            //select
            Role r = roleMapper.getRole(1L);
            System.out.println(r.toString());
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        }finally {
            if(session != null){
                session.close();
            }
        }
    }
}
1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:46172次
    • 积分:653
    • 等级:
    • 排名:千里之外
    • 原创:25篇
    • 转载:0篇
    • 译文:0篇
    • 评论:6条
    文章分类
    最新评论