MyBatis CRUD Java POJO操作

<?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>
    <!-- <settings> <setting name="useGeneratedKeys" value="false"/> <setting 
        name="useColumnLabel" value="true"/> </settings> <typeAliases> <typeAlias 
        alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/> 
        </typeAliases> -->

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value="" />
            </transactionManager>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
                <property name="username" value="root" />
                <property name="password" value="mysql" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/stone/config/sqlxml/Person.xml" />
        <mapper class="com.stone.dao.IPersonMapper"/>
    </mappers>
</configuration>
<?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="Person">

    <resultMap type="com.stone.bean.Person" id="PersonResult">
        <!-- jdbcType就是java.sql.Types.后面的名称 -->
        <id column="ID" jdbcType="INTEGER" property="id" />
        <result column="NAME" jdbcType="VARCHAR" property="name" />
        <result column="BIRTHDAY" jdbcType="TIMESTAMP" property="birthday" />
    </resultMap>

    <select id="queryPersonList" resultMap="PersonResult">
        SELECT ID,NAME,BIRTHDAY
        FROM person
    </select>
    <select id="queryPerson2" resultType="com.stone.bean.Person">
        SELECT ID,NAME,BIRTHDAY
        FROM person
    </select>

    <insert id="insertPerson" parameterType="com.stone.bean.Person">
        insert into
        person(name,birthday) values(#{name},#{birthday});
    </insert>

    <delete id="delPerson" parameterType="int">
        delete from person where
        id=#{id}
    </delete>

    <select id="selPerson" parameterType="int" resultType="com.stone.bean.Person">
        select id,name,birthday from person where id=#{id}
    </select>

    <update id="updatePerson" parameterType="com.stone.bean.Person">
        update person set
        name=#{name},birthday = #{birthday} where id=#{id}
    </update>
    <select id="version" parameterType="long" resultType="int">
        SELECT
        version FROM user WHERE id = #{id,jdbcType=INTEGER}
    </select>

</mapper>
package com.stone.db;

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 DBAccess {
    public SqlSession getSqlSession() throws IOException {
        // 通过数据库文件获取数据库连接
        Reader reader = Resources
                .getResourceAsReader("com/stone/config/Configuration.xml");
        // 通过配置信息构建一个SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(reader);
        // 获取SqlSessionFactory的第二种方法;
        // InputStream inputStream = DBAccess.class
        // .getResourceAsStream("com/stone/config/Configuration.xml");
        // SqlSessionFactory factory = new SqlSessionFactoryBuilder()
        // .build(inputStream);
        // 通过SqlSessoinFactory打开一个数据库会话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}
package com.stone.bean;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Person {

    private int id;
    private String name;
    private Date birthday;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:SS");
        return "Person [id=" + id + ", name=" + name + ", birthday="
                + dateFormat.format(birthday) + "]";
    }

}
package com.stone.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.stone.bean.Person;
import com.stone.db.DBAccess;

public class DBDao {

    public List<Person> queryPerson() {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        List<Person> persons = new ArrayList<Person>();
        try {
            sqlSession = dbAccess.getSqlSession();
            // 通过sqlSession执行SQL语句;
            persons = sqlSession.selectList("Person.queryPersonList");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return persons;
    }

    public List<Person> queryPerson2() {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        List<Person> persons = new ArrayList<Person>();
        try {
            sqlSession = dbAccess.getSqlSession();
            // 通过sqlSession执行SQL语句;
            persons = sqlSession.selectList("Person.queryPerson2");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return persons;
    }

    public void insertPerson(Person person) {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            String statement = "Person.insertPerson";
            // int The number of rows affected by the insert.
            int insert = sqlSession.insert(statement, person);
            System.out.println("insert result:" + insert);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    public void deletePerson(int id) {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            String statement = "Person.delPerson";
            int delete = sqlSession.delete(statement, id);
            System.out.println("delete rownums:" + delete);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    public Person getPerson(int id) {

        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        Person person = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            String statement = "Person.selPerson";
            person = sqlSession.selectOne(statement, id);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return person;
    }

    public int insertPerson2() {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        int insertPerson = -1;
        try {
            sqlSession = dbAccess.getSqlSession();
            IPersonMapper mapper = sqlSession.getMapper(IPersonMapper.class);

            Person person = new Person();
            person.setName("name2");
            person.setBirthday(new Date());
            insertPerson = mapper.insertPerson(person);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return insertPerson;
    }

    public static void main(String[] args) {
        DBDao dbDao = getPersons();
        System.out.println("=================");
        List<Person> persons2 = getPersons2(dbDao);
        System.out.println("=================");
        insertPerson(dbDao);
        System.out.println("=================");
        dbDao.deletePerson(persons2.get(0).getId());
        System.out.println("=================");
        System.out.println(dbDao.getPerson(persons2.get(1).getId()));
        System.out.println("=================");
        System.out.println(dbDao.insertPerson2());
    }

    private static void insertPerson(DBDao dbDao) {
        Person person = new Person();
        person.setName("name");
        person.setBirthday(new Date());
        dbDao.insertPerson(person);
    }

    private static List<Person> getPersons2(DBDao dbDao) {
        List<Person> list2 = dbDao.queryPerson2();
        for (Person person : list2) {
            System.out.println(person);
        }
        return list2;
    }

    private static DBDao getPersons() {
        DBDao dbDao = new DBDao();
        List<Person> list = dbDao.queryPerson();
        System.out.println(list.size());
        for (Person person : list) {
            System.out.println(person);
        }
        return dbDao;
    }
}
package com.stone.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.stone.bean.Person;

public interface IPersonMapper {
    @Insert("insert into person(name,birthday) values(#{name},#{birthday})")
    public int insertPerson(Person person);

    @Delete("delete from person where id=#{id}")
    public int deletePersonById(Person person);

    @Update("update person set name=#{name},birthday=#{birthday} where id=#{id}")
    public int updatePerson(Person person);

    @Select("select id,name,birthday from person where id=#{id}")
    public Person getPersonById(int id);

    @Select("select id,name,birthday from person")
    public List<Person> getPerons();

}
log4j.rootLogger=DEBUG,Console
log4j.appender.Console = org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern =  %d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO
#-------------------------------- 
log4j.logger.java.sql.ResultSet = INFO
log4j.logger.org.apache = INFO
log4j.logger.java.sql.Connection = DEBUG
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG
log4j.logger.com.ibatis = debug

log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug

log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug

log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
    <classpathentry kind="lib" path="lib/mybatis-3.2.8.jar" sourcepath="D:/stono/javasoft/mybatis/mybatis-3-mybatis-3.2.8.zip"/>
    <classpathentry kind="lib" path="lib/mysql-connector-java-5.1.7-bin.jar"/>
    <classpathentry kind="lib" path="lib/log4j-1.2.17.jar"/>
    <classpathentry kind="output" path="bin"/>
</classpath>
原文地址:https://www.cnblogs.com/stono/p/4472486.html