1、mybatis 通过mybatis-generator-core-1.3.2 代码生成:
工具下载地址:
https://code.google.com/p/mybatis/
解压工具包 mybatis-generator-core-1.3.2 找到lib目录 添加 配置文件,根据文档说明执行代码生成:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <!--
使用说明: cmd
cd 安装包存放路径
eg:
cd C:\MybatisCodeBuildTool\lib 执行:
java -jar mybatis-generator-core-1.3.2.jar -configfile 配置文件.xml -overwrite --> <generatorConfiguration>
<!-- 陪在数据库连接驱动 -->
<classPathEntry location="mysql-connector-java-5.1.22-bin.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator>
<property name="suppressDate" value="true" />
</commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/mybatistest" userId="root" password="wangkun">
</jdbcConnection> <javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- model 实体代码生成:
targetPackage:命名空间
targetProject:生成文件目录(需要存在目录) -->
<javaModelGenerator targetPackage="com.rhythmk.model"
targetProject="javacodedir">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator> <sqlMapGenerator targetPackage="com.rhythmk.dao"
targetProject="javacodedir">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator> <javaClientGenerator type="XMLMAPPER"
targetPackage="com.rhythmk.dao" targetProject="javacodedir">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!---
table 代码配置:
tableName: 数据库表名
domainObjectName: 映射对象名 通过下面配置选择生成操作方法,默认为true
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"
-->
<table tableName="MyUser" domainObjectName="MyUser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" >
<!-- ignoreColumn : 排除属性 --->
<ignoreColumn column="Age" /> </table> </context>
</generatorConfiguration>
2、mybatis 增改查:
项目结构:
config.properties:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatistest?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
db.user=root
db.pass=wangkun
SqlMapConfig.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="config.properties"></properties> <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.user}" />
<property name="password" value="${db.pass}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/rhythmk/dao/MyUserMapper.xml"/>
</mappers>
</configuration>
MyUserMapper.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.rhythmk.dao.MyUserMapper">
<resultMap id="BaseResultMap" type="com.rhythmk.model.MyUser">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<id column="ID" jdbcType="TINYINT" property="id" />
<result column="UserName" jdbcType="VARCHAR" property="username" />
<result column="CreateTime" jdbcType="TIMESTAMP" property="createtime" />
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
ID, UserName, CreateTime
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Byte" resultMap="BaseResultMap">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select
<include refid="Base_Column_List" />
from myuser
where ID = #{id,jdbcType=TINYINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Byte">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
delete from myuser
where ID = #{id,jdbcType=TINYINT}
</delete>
<insert id="insert" parameterType="com.rhythmk.model.MyUser">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
insert into myuser (ID, UserName, CreateTime
)
values (#{id,jdbcType=TINYINT}, #{username,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}
)
</insert>
<insert id="insertSelective" parameterType="com.rhythmk.model.MyUser">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
insert into myuser
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
ID,
</if>
<if test="username != null">
UserName,
</if>
<if test="createtime != null">
CreateTime,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=TINYINT},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="createtime != null">
#{createtime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.rhythmk.model.MyUser">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
update myuser
<set>
<if test="username != null">
UserName = #{username,jdbcType=VARCHAR},
</if>
<if test="createtime != null">
CreateTime = #{createtime,jdbcType=TIMESTAMP},
</if>
</set>
where ID = #{id,jdbcType=TINYINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.rhythmk.model.MyUser">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
update myuser
set UserName = #{username,jdbcType=VARCHAR},
CreateTime = #{createtime,jdbcType=TIMESTAMP}
where ID = #{id,jdbcType=TINYINT}
</update> <!-- 设置 参数类型为Map 则可以通过 Map<String,Object>
进行参数化 传值,
同时 parameterType 也可以设置为具体的 JaveBean类型 如上面方法进行查询传值
--> <select id="selectUser" parameterType="Map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from myuser
where ID = #{id,jdbcType=TINYINT} And UserName=#{UserName}
</select> </mapper>
测试代码:
private static SqlSessionFactory sqlSessionFactory = null;
static{
try {
InputStream is= org.apache.ibatis.io.Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(is); } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} } /**
* 添加数据
*/ public static void testInsert()
{
SqlSession session=sqlSessionFactory.openSession();
MyUser user=new MyUser();
user.setCreatetime(new Date());
user.setUsername("RHYTHMK");
session.insert("insert",user);
session.commit(); } /**
* 查询数据
*/
public static void testSelectOne()
{
SqlSession session=sqlSessionFactory.openSession();
try {
MyUser user=session.selectOne("selectByPrimaryKey",1);
System.out.printf(user.getUsername());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
session.close();
}
} /**
* 修改数据
*/
public static void testUpdate()
{
SqlSession session=sqlSessionFactory.openSession();
MyUser user=new MyUser();
user.setCreatetime(new Date());
user.setUsername("RHYTHMK_update");
user.setId(Byte.parseByte("1"));
session.insert("updateByPrimaryKeySelective",user);
session.commit();
} public static void testSelectByMap()
{
Map<String,Object> map=new HashMap<String, Object>();
map.put("id", "2");
map.put("UserName", "wangk2");
SqlSession session=sqlSessionFactory.openSession();
MyUser user=(MyUser)session.selectOne("selectUser", map) ;
System.out.println("testSelect:"+user.getId().toString()); }
相关代码:
http://pan.baidu.com/s/1raUGs