Fork me on GitHub

Mybatisxml配置

<?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="test/properties/mysql.properties"></properties>
    
    <typeAliases>
        <typeAlias type="test.model.Mail" alias="Mail"/>
        <typeAlias type="test.model.Attachment" alias="Attachment"/>        
    </typeAliases>
    
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="UNPOOLED">
                <property name="driver" value="${db_driver}" />
                <property name="url" value="${db_url}" />
                <property name="username" value="${db_user}" />
                <property name="password" value="${db_password}"/>
            </dataSource>
        </environment>
    </environments>  
        
    <mappers>
    <mapper resource="test/data/MailMapper.xml"/>
    <mapper resource="test/data/AttachmentMapper.xml"/>
    </mappers>    
</configuration>

例子:

User.java

package com.mybatis.domain;

public class User {

    private Integer id;//用户id

    private String username;//用户名

    private String password;//密码

    private String address;//地址
。。。。。。。

}

Score.java:

 package com.mybatis.domain;

public class Score {
    
    private Integer id ;//主键id
    
    private User user;//所属用户
    
    private int math ;//数学成绩
    
    private int chinese ;//语文成绩
    
    private int english ;//英语成绩
    
    private int computer ;//计算机成绩
    
    ..........

}

User_Score.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="ScoreDaoMapping">
    <resultMap type="Score" id="score">
        <constructor>
            <idArg column="id" javaType="int" />
            <arg column="userid" javaType="int" />
            <arg column="math" javaType="int" />
            <arg column="chinese" javaType="int" />
            <arg column="english" javaType="int" />
            <arg column="computer" javaType="int" />
        </constructor>
    </resultMap>
    
    <resultMap id="joinSelectScore" type="Score" >
      <id property="id" column="id"/>
      <result property="math" column="math"/>
      <result property="chinese" column="chinese"/>
      <result property="english" column="english"/>
      <result property="computer" column="computer"/>
      <association property="user" column="userid" javaType="User" resultMap="UserDaoMapping.userResult"/>
    </resultMap>
    
    <insert id="insertScore" parameterType="Score">
       insert into pg_score(math,chinese,english,computer,userid) values(#{math},#{chinese},#{english},#{computer},#{user.id})
    </insert>
    
    <select id="findScoreByUser" resultMap="joinSelectScore" resultType="list" parameterType="map">
         select 
                s.id as id,
                s.math as math,
                s.chinese as chinese,
                s.english as english,
                s.computer as computer,
                u.id as userid,
                u.username as username,
                u.password as password,
                u.address as address
         from pg_score s left outer join pg_userinfo u on s.userid = u.id where u.id=#{userid} 
    </select>
    
    <resultMap type="User" id="userResult">
      <id property="id" column="userid"/>
      <result property="username" column="username"/>
      <result property="password" column="password"/>
      <result property="address" column="address"/>
    </resultMap>

   
</mapper>

ScoreDao.java

private  String resource = "com/mybatis/configuration/mybatis.xml";
    public List<Score> selectScoreByUser(User user) throws IOException{
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
        SqlSession session = ssf.openSession();
        reader.close();
        Map<String,Integer> params = new HashMap<String,Integer>();
        params.put("userid", user.getId());
        List<Score> scoreList = session.selectList("ScoreDaoMapping.findScoreByUser", params);
        session.commit();
        session.close();
        return scoreList;
    }

参考网址:http://yangjianzhouctgu.iteye.com/blog/1901608

里外一个例子:参考网址:http://blog.csdn.net/zhangweiwtmdbf/article/details/6641328

package com.company.entity;

import java.util.List;

public class Group {
    private int id;
    private String name;
    private String position;
    private List<Student> students;
    
    
    public List<Student> getStudents() {
        return students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }
    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 String getPosition() {
        return position;
    }
    public void setPosition(String position) {
        this.position = position;
    }
    @Override
    public String toString() {
        return "Group [id=" + id + ", name=" + name + ", position=" + position
                + "]";
    }
    
}
<?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.company.dao.IStudentDAO">
    
    <!-- mybatis缓存 -->
    <cache eviction="LRU" flushInterval="600000" size="1024" readOnly="false" />
    
    <!-- sql标签用来定义一些可以被重用的sql语句或字段或片段等 -->
    <sql id="studentColumns">select id,name,birth from student</sql>
    
    <!-- 此处获得多对一的关系 ,但就单条记录而言却是一对一的关系,所以一对一的写法跟此相同-->
    <resultMap type="Student" id="getStudentAndGroup" >
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="birth" property="birth"/>
        <association property="group" column="group_id" javaType="Group">
            <id column="g_id" property="id"/>
            <result column="g_name" property="name"/>
            <result column="g_position" property="position"/>
        </association>
    </resultMap>
    <select id="many2one" resultMap="getStudentAndGroup" parameterType="int" >
        select s.id,s.name,s.birth,s.group_id,g.g_id,g.g_name,g.g_position 
        from student s 
        left join g_group g on s.group_id = g.g_id
        where s.id = #{id}
    </select>
    
    
    <!-- 意图是获得一个学生,并且获得该学生所属的组,跟上面的意思差不多 ,用association的select属性-->
    <!-- 于上面的相比个人感觉上面的效率要高些,因为上面只有一条sql语句 -->
    <resultMap type="Student" id="getStudentAndGroupUseSelectMap">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="birth" property="birth"/>
        <association property="group" column="group_id" javaType="Group" select="selectGroup" />
    </resultMap>
    <select id="getStudentAndGroupUseSelect" resultMap="getStudentAndGroupUseSelectMap" parameterType="int">
        select * 
        from student 
        where id = #{id}
    </select>
    <select id="selectGroup" resultType="Group" parameterType="int" flushCache="false" useCache="true"><!-- 此处实用缓存 -->
        select g_id as id, g_name as name, g_position as position 
        from g_group 
        where g_id = #{id}
    </select>

    <!-- 动态sql语句 的测试dynamic sql-->    
    <select id="getStudentBySomeCondition" parameterType="Student" resultType="Student">
        select *
        from student
        <where>
            <if test="id != null">
                id>2
            </if>
            <if test="name != null">
                and name like '%g%'
            </if>
        </where>
    </select>
    
    <!-- MyBatis调用存储过程 -->
    <resultMap type="Student" id="studentMap">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="birth" property="birth"/>
    </resultMap>
    <select id="getAllUser" statementType="CALLABLE" >
        {call get_all_student(#{students ,mode=OUT, jdbcType=CURSOR, javaType=ResultSet, resultMap=studentMap} )}
    </select>
    
    
    <!-- MyBatis向student表中插入一条数据 -->
    <insert id="add" parameterType="Student" keyColumn="id">
        <selectKey keyProperty="id" order="BEFORE" resultType="int"> 
            select stu_id_sequence.nextval from dual
        </selectKey>
        insert into student(id,name,birth) values(#{id},#{name},#{birth})
    </insert>
    
    <!-- 根据id获得学生的信息 -->
    <select id="getById" parameterType="int" resultType="Student">
        <include refid="studentColumns"/> where id=#{id}
    </select>
    
    <!-- 此处的实现方法是一个分页的原型,请查看IStudentDAOImpl.java中的调用方法 -->
    <select id="getAllStudent" resultMap="studentMap">
        <include refid="studentColumns"/> order by id<!--此处是引用了上面预定义好的sql语句-->
    </select>
    
    
</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.company.dao.IGroupDAO">
    
    
    
    <resultMap type="Group" id="groupResultMap" >
        <id column="g_id" property="id"/>
        <result column="g_name" property="name"/>
        <result column="g_position" property="position"/>
    </resultMap>
    <sql id="getALl">select * from</sql>
    
    <!-- 意图想通过获得组和组中的所有student,此处相当于one2many -->
    <resultMap type="Group" id="getGroupAndStudents">
        <id column="g_id" property="id"/>
        <result column="g_name" property="name"/>
        <result column="g_position" property="position"/>
        <collection property="students" ofType="Student" column="group_id"><!-- 注意此处的group_id是student表的外键 -->
            <id column="id" property="id"/>
            <result column="name" property="name"/>
            <result column="birth" property="birth"/>
        </collection>
    </resultMap>
    
    
    
    
    
    
    <select id="getById" parameterType="int" resultMap="getGroupAndStudents">
        select g.g_id,g.g_name,g.g_position,s.id,s.name,s.birth ,s.group_id
        from g_group g
        left join student s on g.g_id = s.group_id
        where g.g_id = #{id}
    </select>
    
    <!-- 
    <select id="getById" parameterType="int" resultType="Group">
        select g_id as id, g_name as name, g_position as position from g_group where g_id=#{id}
    </select>
     -->
    <select id="getByIdResultMap" parameterType="_int" resultMap="groupResultMap">
        select g_id ,g_name, g_position  from g_group where g_id=#{id}
    </select>
    <delete id="deleteById" parameterType="_int" timeout="1000">
        delete from g_group where g_id=#{id}
    </delete>
    <insert id="add" parameterType="Group">
        insert into g_group(g_id, g_name, g_position) 
        values(#{id}, #{name}, #{position})
    </insert>
    
</mapper>

原理同第一个例子:

<!-- Result Map -->
    <!-- goods resultmap -->
    <resultMap id="goodsResultMap" type="com.qunar.scoresystem.bean.Goods">
        <id property="goodsId" column="goods_id" />
        <result property="goodsName" column="goods_name" />
        <result property="goodsStorageNum" column="goods_storage_num" />
        <result property="goodsScore" column="goods_score" />
        <result property="goodsDescription" column="goods_description" />
        <result property="goodsStatus" column="goods_status" />
        <collection property="goodsImgList" resultMap="goodsImgResult" />
    </resultMap>

    <!-- goodsimage resultmap -->
    <resultMap id="goodsImgResult" type="com.qunar.scoresystem.bean.GoodsImg">
        <id property="imgId" column="img_id" />
        <result property="goodsId" column="goods_id" />
        <result property="imgDir" column="img_dir" />
        <result property="imgSize" column="img_size" />
        <result property="imgName" column="img_name" />
    </resultMap>
查看复制到剪贴板打印
<?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="User">     
  
    <select id="selectUser" parameterType="int" resultType="UserInfo">     
  
    <![CDATA[     
  
        select * from user_info where id = #{id}     
  
    ]]>     
  
    < lect>     
  
</mapper>    

 

posted on 2014-08-03 01:15  lingfeng95  阅读(268)  评论(0编辑  收藏  举报