MyBatis CRUD Java POJO操作

<?xml version="1.0" encoding="UTF-8" ?>
<!-- Copyright 2009-2012 the original author or authors. Licensed under the
    Apache License, Version 2.0 (the "License"); you may not use this file except
    in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software distributed
    under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
    OR CONDITIONS OF ANY KIND, either express or implied. See the License for
    the specific language governing permissions and limitations under the License. -->
<!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"?>
<!-- Copyright 2009-2012 the original author or authors. Licensed under the
    Apache License, Version 2.0 (the "License"); you may not use this file except
    in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software distributed
    under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
    OR CONDITIONS OF ANY KIND, either express or implied. See the License for
    the specific language governing permissions and limitations under the License. -->

<!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();

}
时间: 2024-12-16 02:16:45

MyBatis CRUD Java POJO操作的相关文章

Java程序操作数据库SQLserver详解

数据库基本操作:增删改查(CRUD) crud介绍(增.删.改.查操作) CRUD是指在做计算处理时的增加(Create).查询(Retrieve)(重新得到数据).更新(Update)和删除(Delete)几个单记事的首字母简写.主要被用在描述软件系统中数据库或者持久层的基本操作功能. Create new records Rctricvc cxisting rccords Update existing records Delete existing records. 要对数据表进行增.删.

Java开发--操作MongoDB

http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html介绍到了在MongoDB的控制台完成MongoDB的数据操作,通过前一篇文章我们对MongoDB有了全面的认识和理解.现在我们就用Java来操作MongoDB的数据. 开发环境: System:Windows IDE:eclipse.MyEclipse 8 Database:mongoDB 开发依赖库: JavaEE5.mongo-2.5.3.jar.junit-4.8.2.j

Java API操作HDFS

HDFS是存储数据的分布式文件系统,对HDFS的操作,就是对文件系统的操作,除了用HDFS的shell命令对文件系统进行操作,我们也可以利用Java API对文件系统进行操作,比如文件的创建.删除.修改权限等等,还有文件夹的创建.删除.重命名等等. 使用Java API对文件系统进行操作主要涉及以下几个类: 1.Configuration类:该类的对象封装了客户端或者服务端的配置. 2.FileSystem类:该类的对象是一个文件系统对象,可以利用该对象的一些方法来对文件进行操作,FileSys

JAVA批处理操作

批处理,可以大幅度提升大量增.删.改的速度,就是对大数据操作有很大的效率提升. 与上篇文章中提到的"连接池"相似.其实就是先将多次操作(增删改)打包,然后再一次发送执行 主要用到两个方法: ?  打包:PreparedStatement.addBatch(); ?  发送.执行:PreparedStatement.executeBatch(); 下面看做同一件事,用批处理和不用批处理的效率对比,源码如下: import java.sql.Connection; import java.

Mybatis Mapper.java和Mapper.xml能否分离问题

Mybatis Mapper.java和Mapper.xml是能分离的. 从图上不难看出,不管是/java还是/resources,他们最终编译后的存放路径均是/target/classes 因此将xml和java分开就成了一件简单的事了 方法: 只需要在resource目录下创建和java下的mapper.java相同的路径,然后将对应的mapper.xml放入该目录下就行了 ok完事...

Java File操作汇总

作者:卿笃军 原文地址:http://blog.csdn.net/qingdujun/article/details/41223841 本文通过大量的示例,介绍和讲解了Java File操作. 1)创建文件  2)删除文件  3)判断文件是否存在  4)创建文件夹  5)文件类型判断  6)获取文件信息 7)获取目录下文件名  8)递归打印所有文件名  9)递归删除整个文件夹  10)Properties类 11)SequenceInputStream类:连接多个流  12)对象序列化实现Ser

Hadoop读书笔记(三)Java API操作HDFS

Hadoop读书笔记(一)Hadoop介绍:http://blog.csdn.net/caicongyang/article/details/39898629 Hadoop读书笔记(二)HDFS的shell操作:http://blog.csdn.net/caicongyang/article/details/41253927 JAVA URL 操作HDFS OperateByURL.java package hdfs; import java.io.InputStream; import jav

Java字节流操作

在java.io包中得操作主要有字节流与字符流两大类,两个类都有输入输出操作. 在字节流中,输出数据主要使用OutputStream类,输入使用的InputStream类. 在字符流中,输出数据使用Writer,输入数据使用Reader. 在Java中IO操作有相应的步骤,以文件的操作为例. (1)使用File类打开一个文件 (2)通过字节流或字符流的子类指定输出的位置. (3)进行读/写操作 (4)关闭输入/输出 字符流与字节流的区别: 字节流在操作时本身不会用到缓冲区(内存),是文件本身直接

HDFS基础和java api操作

1. 概括 适合一次写入多次查询情况,不支持并发写情况 通过hadoop shell 上传的文件存放在DataNode的block中,通过linux shell只能看见block,看不见文件(HDFS将客户端的大文件存放在很多节点的数据块中,Block本质上是一个逻辑概念,它是hdfs读写数据的基本单位) HDFS中,如果一个文件小于一个数据块的大小,并不占用整个数据块存储空间 2. fs 可以使用hdfs shell操作hdfs,常用 fs命令如下: eg: hadoop fs -cat fi