论坛首页 Java企业应用论坛

Mybatis3.0查询,保存,更新,删除数据。

浏览 77017 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (3) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-02-08   最后修改:2012-02-08
源代码http://eassen.iteye.com/blog/1399002

近来打算开发一个技术框架,并应用此框架开发出一个论坛,开始打算用sturts2+spring+hibernate+jquery为基础,然后再进行封装,最后形成技术框架,但通过此网站获知mybatis比hibernate更灵活,实用。因此开始逐步接触mybatis。

以下是mybatis3.0的开发实例,使用的java环境jdk5.0,ide为eclipse3.7,数据库是oracle11g。

1.数据环境配置

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd">
  3. <configuration>
  4. <!-- - - - - - - 数据库环境配置- - - - - - - - - -->
  5. <environments default="environments">
  6. <environment id="eassen">
  7. <transactionManager type="JDBC"/>
  8. <dataSource type="POOLED">
  9. <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
  10. <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:eassen"/>
  11. <property name="username" value="eassen"/>
  12. <property name="password" value="oracle"/>
  13. </dataSource>
  14. </environment>
  15. </environments>
  16. <!-- - - - - - - -映射文件路径- - - - - - -->
  17. <mappers>
  18. <mapper resource="com/pojo/sql/DmMydwtMapper.xml"/>
  19. </mappers>
  20. </configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd">

<configuration>
    <!-- - - - - - - 数据库环境配置- - - - - - - - - -->
    <environments default="environments">
        <environment id="eassen">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:eassen"/>
                <property name="username" value="eassen"/>
                <property name="password" value="oracle"/>
            </dataSource>
        </environment>
    </environments>
    <!-- - - - - - - -映射文件路径- - - - - - -->
    <mappers>
        <mapper resource="com/pojo/sql/DmMydwtMapper.xml"/>
    </mappers>
</configuration>

2.数据库表映射(DM_MYDWT)XML文件

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.dao.DmMydwtMapper">
  5. <resultMap id="BaseResultMap" type="com.pojo.DmMydwt">
  6. <id column="MYDWT_DM" property="mydwtDm" jdbcType="CHAR" javaType="String" />
  7. <result column="MYDWT_MC" property="mydwtMc" jdbcType="VARCHAR"
  8. javaType="String" />
  9. <result column="YXBZ" property="yxbz" jdbcType="CHAR" javaType="String" />
  10. <result column="XYBZ" property="xybz" jdbcType="CHAR" javaType="String" />
  11. </resultMap>
  12. <sql id="Base_Column_List">
  13. MYDWT_DM, MYDWT_MC, YXBZ, XYBZ
  14. </sql>
  15. <select id="selectByPrimaryKey" resultMap="BaseResultMap"
  16. parameterType="java.lang.String">
  17. select
  18. <include refid="Base_Column_List" />
  19. from EASSEN.DM_MYDWT
  20. where MYDWT_DM = #{mydwtDm,jdbcType=CHAR}
  21. </select>
  22. <delete id="deleteByPrimaryKey" parameterType="java.lang.String"
  23. flushCache="true">
  24. delete from EASSEN.DM_MYDWT
  25. where MYDWT_DM =
  26. #{mydwtDm,jdbcType=CHAR}
  27. </delete>
  28. <insert id="insert" parameterType="com.pojo.DmMydwt" flushCache="true">
  29. insert into EASSEN.DM_MYDWT (MYDWT_DM, MYDWT_MC, YXBZ,
  30. XYBZ)
  31. values
  32. (#{mydwtDm,jdbcType=CHAR}, #{mydwtMc,jdbcType=VARCHAR},
  33. #{yxbz,jdbcType=CHAR},
  34. #{xybz,jdbcType=CHAR})
  35. </insert>
  36. <insert id="insertSelective" parameterType="com.pojo.DmMydwt"
  37. flushCache="true">
  38. insert into EASSEN.DM_MYDWT
  39. <trim prefix="(" suffix=")" suffixOverrides=",">
  40. MYDWT_DM,
  41. MYDWT_MC,
  42. YXBZ,
  43. XYBZ,
  44. </trim>
  45. <trim prefix="values (" suffix=")" suffixOverrides=",">
  46. #{mydwtDm,jdbcType=CHAR},
  47. #{mydwtMc},
  48. #{yxbz,jdbcType=CHAR},
  49. #{xybz,jdbcType=CHAR},
  50. </trim>
  51. </insert>
  52. <update id="updateByPrimaryKeySelective" parameterType="com.pojo.DmMydwt"
  53. flushCache="true">
  54. update EASSEN.DM_MYDWT
  55. <set>
  56. <if test="mydwtMc != null">
  57. MYDWT_MC = #{mydwtMc,jdbcType=VARCHAR},
  58. </if>
  59. <if test="yxbz != null">
  60. YXBZ = #{yxbz,jdbcType=CHAR},
  61. </if>
  62. <if test="xybz != null">
  63. XYBZ = #{xybz,jdbcType=CHAR},
  64. </if>
  65. </set>
  66. where MYDWT_DM = #{mydwtDm,jdbcType=CHAR}
  67. </update>
  68. <update id="updateByPrimaryKey" parameterType="com.pojo.DmMydwt"
  69. flushCache="true">
  70. update EASSEN.DM_MYDWT
  71. set MYDWT_MC =
  72. #{mydwtMc,jdbcType=VARCHAR},
  73. YXBZ = #{yxbz,jdbcType=CHAR},
  74. XYBZ =
  75. #{xybz,jdbcType=CHAR}
  76. where MYDWT_DM = #{mydwtDm,jdbcType=CHAR}
  77. </update>
  78. </mapper>
<?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.dao.DmMydwtMapper">
	<resultMap id="BaseResultMap" type="com.pojo.DmMydwt">
		<id column="MYDWT_DM" property="mydwtDm" jdbcType="CHAR" javaType="String" />
		<result column="MYDWT_MC" property="mydwtMc" jdbcType="VARCHAR"
			javaType="String" />
		<result column="YXBZ" property="yxbz" jdbcType="CHAR" javaType="String" />
		<result column="XYBZ" property="xybz" jdbcType="CHAR" javaType="String" />
	</resultMap>
	<sql id="Base_Column_List">
		MYDWT_DM, MYDWT_MC, YXBZ, XYBZ
	</sql>
	<select id="selectByPrimaryKey" resultMap="BaseResultMap"
		parameterType="java.lang.String">
		select
		<include refid="Base_Column_List" />
		from EASSEN.DM_MYDWT
		where MYDWT_DM = #{mydwtDm,jdbcType=CHAR}
	</select>
	<delete id="deleteByPrimaryKey" parameterType="java.lang.String"
		flushCache="true">
		delete from EASSEN.DM_MYDWT
		where MYDWT_DM =
		#{mydwtDm,jdbcType=CHAR}
	</delete>
	<insert id="insert" parameterType="com.pojo.DmMydwt" flushCache="true">
		insert into EASSEN.DM_MYDWT (MYDWT_DM, MYDWT_MC, YXBZ,
		XYBZ)
		values
		(#{mydwtDm,jdbcType=CHAR}, #{mydwtMc,jdbcType=VARCHAR},
		#{yxbz,jdbcType=CHAR},
		#{xybz,jdbcType=CHAR})
	</insert>
	<insert id="insertSelective" parameterType="com.pojo.DmMydwt"
		flushCache="true">
		insert into EASSEN.DM_MYDWT
		<trim prefix="(" suffix=")" suffixOverrides=",">
			MYDWT_DM,
			MYDWT_MC,
			YXBZ,
			XYBZ,
		</trim>
		<trim prefix="values (" suffix=")" suffixOverrides=",">
			#{mydwtDm,jdbcType=CHAR},
			#{mydwtMc},
			#{yxbz,jdbcType=CHAR},
			#{xybz,jdbcType=CHAR},
		</trim>
	</insert>
	<update id="updateByPrimaryKeySelective" parameterType="com.pojo.DmMydwt"
		flushCache="true">
		update EASSEN.DM_MYDWT
		<set>
			<if test="mydwtMc != null">
				MYDWT_MC = #{mydwtMc,jdbcType=VARCHAR},
			</if>
			<if test="yxbz != null">
				YXBZ = #{yxbz,jdbcType=CHAR},
			</if>
			<if test="xybz != null">
				XYBZ = #{xybz,jdbcType=CHAR},
			</if>
		</set>
		where MYDWT_DM = #{mydwtDm,jdbcType=CHAR}
	</update>
	<update id="updateByPrimaryKey" parameterType="com.pojo.DmMydwt"
		flushCache="true">
		update EASSEN.DM_MYDWT
		set MYDWT_MC =
		#{mydwtMc,jdbcType=VARCHAR},
		YXBZ = #{yxbz,jdbcType=CHAR},
		XYBZ =
		#{xybz,jdbcType=CHAR}
		where MYDWT_DM = #{mydwtDm,jdbcType=CHAR}
	</update>
</mapper>

3.数据库表(DM_MYDWT)java

Java代码 复制代码 收藏代码
  1. package com.pojo;
  2. import java.io.Serializable;
  3. public class DmMydwt implements Serializable {
  4. /**
  5. *
  6. */
  7. private static final long serialVersionUID = 1078518054837885063L;
  8. /**
  9. * EASSEN.DM_MYDWT.MYDWT_DM
  10. * @ibatorgenerated 2012-02-05 20:14:30
  11. */
  12. private String mydwtDm;
  13. /**
  14. * EASSEN.DM_MYDWT.MYDWT_MC
  15. * @ibatorgenerated 2012-02-05 20:14:30
  16. */
  17. private String mydwtMc;
  18. /**
  19. * EASSEN.DM_MYDWT.YXBZ
  20. * @ibatorgenerated 2012-02-05 20:14:30
  21. */
  22. private String yxbz;
  23. /**
  24. * EASSEN.DM_MYDWT.XYBZ
  25. * @ibatorgenerated 2012-02-05 20:14:30
  26. */
  27. private String xybz;
  28. public String getMydwtDm() {
  29. return mydwtDm;
  30. }
  31. public void setMydwtDm(String mydwtDm) {
  32. this.mydwtDm = mydwtDm;
  33. }
  34. public String getMydwtMc() {
  35. return mydwtMc;
  36. }
  37. public void setMydwtMc(String mydwtMc) {
  38. this.mydwtMc = mydwtMc;
  39. }
  40. public String getYxbz() {
  41. return yxbz;
  42. }
  43. public void setYxbz(String yxbz) {
  44. this.yxbz = yxbz;
  45. }
  46. public String getXybz() {
  47. return xybz;
  48. }
  49. public void setXybz(String xybz) {
  50. this.xybz = xybz;
  51. }
  52. }
package com.pojo;

import java.io.Serializable;

public class DmMydwt implements Serializable {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1078518054837885063L;

	/**
     * EASSEN.DM_MYDWT.MYDWT_DM
     * @ibatorgenerated 2012-02-05 20:14:30
     */
    private String mydwtDm;

    /**
     * EASSEN.DM_MYDWT.MYDWT_MC
     * @ibatorgenerated 2012-02-05 20:14:30
     */
    private String mydwtMc;

    /**
     * EASSEN.DM_MYDWT.YXBZ
     * @ibatorgenerated 2012-02-05 20:14:30
     */
    private String yxbz;

    /**
     * EASSEN.DM_MYDWT.XYBZ
     * @ibatorgenerated 2012-02-05 20:14:30
     */
    private String xybz;

    public String getMydwtDm() {
        return mydwtDm;
    }

    public void setMydwtDm(String mydwtDm) {
        this.mydwtDm = mydwtDm;
    }

    public String getMydwtMc() {
        return mydwtMc;
    }

    public void setMydwtMc(String mydwtMc) {
        this.mydwtMc = mydwtMc;
    }

    public String getYxbz() {
        return yxbz;
    }

    public void setYxbz(String yxbz) {
        this.yxbz = yxbz;
    }

    public String getXybz() {
        return xybz;
    }

    public void setXybz(String xybz) {
        this.xybz = xybz;
    }
}

 

4.DAO

Java代码 复制代码 收藏代码
  1. package com.dao;
  2. import com.pojo.DmMydwt;
  3. public interface DmMydwtMapper {
  4. /**
  5. * 根据主键删除
  6. * 参数:主键
  7. * 返回:删除个数
  8. * @ibatorgenerated 2012-02-05 20:14:58
  9. */
  10. int deleteByPrimaryKey(String mydwtDm);
  11. /**
  12. * 插入,空属性也会插入
  13. * 参数:pojo对象
  14. * 返回:删除个数
  15. * @ibatorgenerated 2012-02-05 20:14:58
  16. */
  17. int insert(DmMydwt record);
  18. /**
  19. * 插入,空属性不会插入
  20. * 参数:pojo对象
  21. * 返回:删除个数
  22. * @ibatorgenerated 2012-02-05 20:14:58
  23. */
  24. int insertSelective(DmMydwt record);
  25. /**
  26. * 根据主键查询
  27. * 参数:查询条件,主键值
  28. * 返回:对象
  29. * @ibatorgenerated 2012-02-05 20:14:58
  30. */
  31. DmMydwt selectByPrimaryKey(String mydwtDm);
  32. /**
  33. * 根据主键修改,空值条件不会修改成null
  34. * 参数:1.要修改成的值
  35. * 返回:成功修改个数
  36. * @ibatorgenerated 2012-02-05 20:14:58
  37. */
  38. int updateByPrimaryKeySelective(DmMydwt record);
  39. /**
  40. * 根据主键修改,空值条件会修改成null
  41. * 参数:1.要修改成的值
  42. * 返回:成功修改个数
  43. * @ibatorgenerated 2012-02-05 20:14:58
  44. */
  45. int updateByPrimaryKey(DmMydwt record);
  46. }
package com.dao;

import com.pojo.DmMydwt;

public interface DmMydwtMapper {
    /**
     * 根据主键删除
     * 参数:主键
     * 返回:删除个数
     * @ibatorgenerated 2012-02-05 20:14:58
     */
    int deleteByPrimaryKey(String mydwtDm);

    /**
     * 插入,空属性也会插入
     * 参数:pojo对象
     * 返回:删除个数
     * @ibatorgenerated 2012-02-05 20:14:58
     */
    int insert(DmMydwt record);

    /**
     * 插入,空属性不会插入
     * 参数:pojo对象
     * 返回:删除个数
     * @ibatorgenerated 2012-02-05 20:14:58
     */
    int insertSelective(DmMydwt record);

    /**
     * 根据主键查询
     * 参数:查询条件,主键值
     * 返回:对象
     * @ibatorgenerated 2012-02-05 20:14:58
     */
    DmMydwt selectByPrimaryKey(String mydwtDm);

    /**
     * 根据主键修改,空值条件不会修改成null
     * 参数:1.要修改成的值
     * 返回:成功修改个数
     * @ibatorgenerated 2012-02-05 20:14:58
     */
    int updateByPrimaryKeySelective(DmMydwt record);

    /**
     * 根据主键修改,空值条件会修改成null
     * 参数:1.要修改成的值
     * 返回:成功修改个数
     * @ibatorgenerated 2012-02-05 20:14:58
     */
    int updateByPrimaryKey(DmMydwt record);
}

 

5.mybatis加载

Java代码 复制代码 收藏代码
  1. package com.db;
  2. import java.io.IOException;
  3. import java.io.Reader;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. public class ConnectionFactory {
  9. private static SqlSessionFactory factory;
  10. private static SqlSession sqlSession = null;
  11. // 读取MyBatis配置文件,创建SqlSessionFactory
  12. static {
  13. try {
  14. Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
  15. factory = new SqlSessionFactoryBuilder().build(reader, "eassen");
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. /**
  21. * 获取SqlSession
  22. * @return
  23. */
  24. public static SqlSession getSession() {
  25. if(sqlSession == null){
  26. sqlSession = factory.openSession();
  27. }
  28. return sqlSession;
  29. }
  30. /**
  31. * 从配置文件中获取数据库表映射对象信息
  32. * @param mapper
  33. * @return
  34. */
  35. public static <T> T getMapper(Class<T> mapper) {
  36. SqlSession session = getSession();
  37. return (T) session.getMapper(mapper);
  38. }
  39. /**
  40. * 数据提交
  41. */
  42. public static void commit(){
  43. sqlSession.commit();
  44. }
  45. /**
  46. * 数据回滚
  47. */
  48. public static void rollback(){
  49. sqlSession.rollback();
  50. }
  51. /**
  52. * 关闭sqlsession
  53. */
  54. public static void close(){
  55. if(sqlSession != null){
  56. sqlSession.close();
  57. }
  58. }
  59. }
package com.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 ConnectionFactory {
    private static SqlSessionFactory factory;
    private static SqlSession sqlSession = null;

    
    // 读取MyBatis配置文件,创建SqlSessionFactory
    static {
        try {
            Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
            factory = new SqlSessionFactoryBuilder().build(reader, "eassen");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession
     * @return
     */
    public static SqlSession getSession() {
    	if(sqlSession == null){
    		sqlSession = factory.openSession();
    	}
        return sqlSession;
    }

    /**
     * 从配置文件中获取数据库表映射对象信息
     * @param mapper
     * @return
     */
    public static <T> T getMapper(Class<T> mapper) {
        SqlSession session = getSession();
        return (T) session.getMapper(mapper);
    }
    
    /**
     * 数据提交
     */
    public static void commit(){
    	sqlSession.commit();
    }
    /**
     * 数据回滚
     */
    public static void rollback(){
    	sqlSession.rollback();
    }
    /**
     * 关闭sqlsession
     */
    public static void close(){
    	if(sqlSession != null){
    		sqlSession.close();
    	}
    }
    
    
}

6.数据查询,插入,更新,删除测试

Java代码 复制代码 收藏代码
  1. package com.test;
  2. import com.dao.DmMydwtMapper;
  3. import com.db.ConnectionFactory;
  4. import com.pojo.DmMydwt;
  5. public class MydTest {
  6. public static void main(String[] args) {
  7. try {
  8. // 获取对象
  9. DmMydwtMapper mydwtMapper = ConnectionFactory
  10. .getMapper(com.dao.DmMydwtMapper.class);
  11. // 查询相关MYDWT_DM为“1001”的信息
  12. DmMydwt mydwt = mydwtMapper.selectByPrimaryKey("1001");
  13. System.out.println("mybatis查询测试:=================================");
  14. System.out.println("MYDWT_DM:" + mydwt.getMydwtDm());
  15. System.out.println("MYDWT_MC:" + mydwt.getMydwtMc());
  16. // 插入数据
  17. System.out.println("mybatis保存测试:=================================");
  18. mydwt = new DmMydwt();
  19. mydwt.setMydwtDm("aaaa");
  20. mydwt.setMydwtMc("mybatis保存");
  21. mydwt.setYxbz("Y");
  22. mydwt.setXybz("Y");
  23. mydwtMapper.insert(mydwt);
  24. // 更新数据
  25. System.out.println("mybatis更新测试:=================================");
  26. mydwt.setMydwtMc(new String("mybatis保存".getBytes(),"UTF-8"));
  27. mydwtMapper.updateByPrimaryKey(mydwt);
  28. // 删除数据
  29. System.out.println("mybatis删除测试:=================================");
  30. mydwtMapper.deleteByPrimaryKey("1001");
  31. ConnectionFactory.commit();
  32. } catch (Exception e) {
  33. ConnectionFactory.rollback();
  34. e.printStackTrace();
  35. } finally {
  36. // 关闭sqlsession
  37. ConnectionFactory.close();
  38. }
  39. }
  40. }
package com.test;

import com.dao.DmMydwtMapper;
import com.db.ConnectionFactory;
import com.pojo.DmMydwt;

public class MydTest {

	public static void main(String[] args) {
		try {
			// 获取对象
			DmMydwtMapper mydwtMapper = ConnectionFactory
					.getMapper(com.dao.DmMydwtMapper.class);

			// 查询相关MYDWT_DM为“1001”的信息
			DmMydwt mydwt = mydwtMapper.selectByPrimaryKey("1001");
			System.out.println("mybatis查询测试:=================================");
			System.out.println("MYDWT_DM:" + mydwt.getMydwtDm());
			System.out.println("MYDWT_MC:" + mydwt.getMydwtMc());
			
			// 插入数据
			System.out.println("mybatis保存测试:=================================");
			mydwt = new DmMydwt();
			mydwt.setMydwtDm("aaaa");
			mydwt.setMydwtMc("mybatis保存");
			mydwt.setYxbz("Y");
			mydwt.setXybz("Y");
			mydwtMapper.insert(mydwt);
			// 更新数据
			System.out.println("mybatis更新测试:=================================");
			mydwt.setMydwtMc(new String("mybatis保存".getBytes(),"UTF-8"));
			mydwtMapper.updateByPrimaryKey(mydwt);
			
			// 删除数据
			System.out.println("mybatis删除测试:=================================");
			mydwtMapper.deleteByPrimaryKey("1001");
			ConnectionFactory.commit();
		} catch (Exception e) {
			ConnectionFactory.rollback();
			e.printStackTrace();
		} finally {
			// 关闭sqlsession
			ConnectionFactory.close();
		}
	}
}

7.控制台信息输出

Java代码 复制代码 收藏代码
  1. 2012-02-08 11:43:01 Logging initialized using 'org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl' adapter.
  2. 2012-02-08 11:43:01 PooledDataSource forcefully closed/removed all connections.
  3. 2012-02-08 11:43:01 PooledDataSource forcefully closed/removed all connections.
  4. 2012-02-08 11:43:01 PooledDataSource forcefully closed/removed all connections.
  5. 2012-02-08 11:43:01 PooledDataSource forcefully closed/removed all connections.
  6. 2012-02-08 11:43:02 Created connection 17671659.
  7. 2012-02-08 11:43:02 ooo Connection Opened
  8. 2012-02-08 11:43:02 ==> Executing: select MYDWT_DM, MYDWT_MC, YXBZ, XYBZ from EASSEN.DM_MYDWT where MYDWT_DM = ?
  9. 2012-02-08 11:43:02 ==> Parameters: 1001(String)
  10. 2012-02-08 11:43:02 <== Columns: MYDWT_DM, MYDWT_MC, YXBZ, XYBZ
  11. 2012-02-08 11:43:02 <== Row: 1001, 您经常访问的网站包括:, Y, Y
  12. mybatis查询测试:=================================
  13. MYDWT_DM:1001
  14. MYDWT_MC:您经常访问的网站包括:
  15. mybatis保存测试:=================================
  16. 2012-02-08 11:43:02 ==> Executing: insert into EASSEN.DM_MYDWT (MYDWT_DM, MYDWT_MC, YXBZ, XYBZ) values (?, ?, ?, ?)
  17. 2012-02-08 11:43:02 ==> Parameters: aaaa(String), mybatis保存(String), Y(String), Y(String)
  18. mybatis更新测试:=================================
  19. 2012-02-08 11:43:02 ==> Executing: update EASSEN.DM_MYDWT set MYDWT_MC = ?, YXBZ = ?, XYBZ = ? where MYDWT_DM = ?
  20. 2012-02-08 11:43:02 ==> Parameters: mybatis保存(String), Y(String), Y(String), aaaa(String)
  21. mybatis删除测试:=================================
  22. 2012-02-08 11:43:02 ==> Executing: delete from EASSEN.DM_MYDWT where MYDWT_DM = ?
  23. 2012-02-08 11:43:02 ==> Parameters: 1001(String)
  24. 2012-02-08 11:43:02 xxx Connection Closed
  25. 2012-02-08 11:43:02 Returned connection 17671659 to pool.
   发表时间:2012-02-10  

关于Mybatis3的更新操作,常见有以下两种:

 

第一种:

	<update id="updateBySelected" parameterType="users">
		update users
		<set>
			<if test="name!=null">user_name = #{name}</if>
			<if test="addr!=null">user_addr = #{addr}</if>
		</set>
		where user_id=#{id}
	</update>
	

 

第二种:

	<update id="update" parameterType="users">
		update users set user_name = #{name}, user_addr = #{addr}
		where user_id=#{id}
	</update>

 

个人认为有时候还是有需要将字段值设置为null的,比如清空日期字段。因此,针对只更新某一两个字段值的情况,我一般是这样操作的:

// 只更新用户姓名(前台页面只传入id、name)
User user = userService.findById(id);//根据用户ID获取缓存的用户对象
user.setName(name);//更新用户姓名
userService.update(user);//同时更新User表所有字段值

 

不知道楼主是如何操作的(只更新某些字段)?

 

 

 

0 请登录后投票
   发表时间:2012-02-11  
mybatis我都用了几年了。。。。
0 请登录后投票
   发表时间:2012-02-11  
可以看一下mybatis和spring结合的新方法
http://sourceforge.net/projects/ibatisjpetstore/
0 请登录后投票
   发表时间:2012-02-13   最后修改:2012-02-13

[quote="duanzonglong"]可以看一下mybatis和spring结合的新方法

http://sourceforge.net/projects/ibatisjpetstore/[/quote]

 

恩,引入spring,就可以这么来了:

 

<!-- DAO层由 MapperScannerConfigurer自动生成mapper bean -->
		<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
				<property name="basePackage" value="com.sample.mapper" />
		</bean>

直接由MapperScannerConfigurer.class扫描mapper接口生成对应的DAO。

0 请登录后投票
   发表时间:2012-02-13  
没写分页啊,这些都没什么用。
0 请登录后投票
   发表时间:2012-02-13  
tomleader 写道
没写分页啊,这些都没什么用。

分页网上蛮多吧
0 请登录后投票
   发表时间:2012-02-13  
private static SqlSession sqlSession = null;

多线程环境不会出错?
0 请登录后投票
   发表时间:2012-02-13  
private static SqlSession sqlSession = null;
public static SqlSession getSession() { 
    if(sqlSession == null){ 
        sqlSession = factory.openSession(); 
    } 
    return sqlSession; 


高并发怎么处理?
0 请登录后投票
   发表时间:2012-02-13  
zjfcyefeng 写道
private static SqlSession sqlSession = null;
public static SqlSession getSession() { 
    if(sqlSession == null){ 
        sqlSession = factory.openSession(); 
    } 
    return sqlSession; 


高并发怎么处理?


他那个有问题,session不能静态的。我提供一个吧

 

/**session 模板类
	 * @author zhz
	 *
	 */
	public static class SqlSessionTemplate {
		SqlSessionFactory sqlSessionFactory;
		
		public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
			this.sqlSessionFactory = sqlSessionFactory;
			
		}

		/**执行sql语句的方法
		 * @param action
		 * @return
		 */
		public Object execute(SqlSessionCallback action)  {
			SqlSession session = null;
			try {
				session = sqlSessionFactory.openSession();
				//设置事务手动提交,如果省略,事务会自动提交,则spring配置文件声明式事务不生效
				session.getConnection().setAutoCommit(false);
//				============================================
        		Object result = action.doInSession(session);
				return result;
			} catch (SQLException e) {
				e.printStackTrace();
			}finally {
				if(session != null) session.close();
			}
			return null;
		}
		
		/**查询一条记录功能
		 * @param statement sql语句
		 * @param parameter 参数
		 * @return
		 */
		public Object selectOne(final String statement,final Object parameter) {
			return execute(new SqlSessionCallback() {
				public Object doInSession(SqlSession session) {
					return session.selectOne(statement, parameter);
				}
			});
		}
		
		/**查询多条记录功能
		 * @param statement  sql语句
		 * @param parameter 查询的对象
		 * @param offset list的起点
		 * @param limit   记录条数
		 * @return
		 */
		public List selectList(final String statement,final Object parameter,final int offset,final int limit) {
			return (List)execute(new SqlSessionCallback() {
				public Object doInSession(SqlSession session) {
					return session.selectList(statement, parameter, new RowBounds(offset,limit));
				}
			});
		}
		
		/**查询多条记录功能
		 * @param statement sql语句
		 * @param parameter 查询的对象
		 * @return
		 */
		public List selectList(final String statement,final Object parameter) {
			return (List)execute(new SqlSessionCallback() {
				public Object doInSession(SqlSession session) {
					return session.selectList(statement, parameter);
				}
			});
		}
		/** 删除
		 * @param statement sql语句
		 * @param parameter 删除的对象
		 * @return
		 */
		public int delete(final String statement,final Object parameter) {
			return (Integer)execute(new SqlSessionCallback() {
				public Object doInSession(SqlSession session) {
					return session.delete(statement, parameter);
				}
			});
		}
		
		/**更新
		 * @param statement 更新sql语句
		 * @param parameter
		 * @return
		 */
		public int update(final String statement,final Object parameter) {
			return (Integer)execute(new SqlSessionCallback() {
				public Object doInSession(SqlSession session) {
					return session.update(statement, parameter);
				}
			});
		}
		
		/**插入
		 * @param statement 插入sql语句
		 * @param parameter
		 * @return
		 */
		public int insert(final String statement,final Object parameter) {
			return (Integer)execute(new SqlSessionCallback() {
				public Object doInSession(SqlSession session) {
					try {
						session.getConnection().setAutoCommit(false);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return session.insert(statement, parameter);
				}
			});
		}
	}

  其实spring也提供了sqlSessionTemplate类。mybatis没有ibatis的daoSupport支持了。。。

0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics