SSM-MyBatis教程(一)-ORMpping技术|动态SQL|MyBatis实现1:1 以及 1:N关联关系|MyBatis逆向工程|综合案例|ResultMapping(详细)

SSM-MyBatis

1、SSM:

​ SSM:Spring SpringMVC MyBaits 缩写,SSI:Spring SpringMVC iBatis,SSH:Spring Struts Hibernate

​ 关于Hibernate和MyBatis,同属于持久化技术(数据持久化),

​ ORMapping技术:对象关系映射技术,将一个对象(User对象)映射成一行表数据(表中一条记录)

​ User user =new User();//

​ iBatis:是MyBatis的早期版本,iBatis升级到3.0时,将iBatis更名为MyBatis

​ Struts : mvc框架 Struts和SpringMVC的功能一致

2、MyBatis:MyBatis是一个轻量级的持久化框架(ORMapping技术)

3、MyBatis-基本的CURD操作以及MyBatis配置文件映射文件配置

①、导入jar包

aopalliance-1.0.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar
hamcrest-core-1.3.jar
junit-4.12.jar
log4j-1.2.17.jar
mybatis-3.2.8.jar
mybatis-generator-core-1.3.5.jar
mybatis-spring-1.1.1.jar
mysql-connector-java-5.1.22-bin.jar
ojdbc14.jar

②、配置MyBatis



<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/newsystem"/>
        <property name="username" value="root"/>
        <property name="password" value="admin"/>
      dataSource>
    environment>
  environments>
  <mappers>
    <mapper resource="com/rock/dao/UserMapper.xml"/>
  mappers>
configuration>

③、配置映射文件



  
<mapper namespace="com.rock.dao.UserDao">

	<delete id="deleteUser" parameterType="java.lang.String">
		delete from user where userid=#{userid}	
	delete>
	<delete id="deleteUserByUser" parameterType="com.rock.entities.User">
		delete from user where userid=#{userid}	
	delete>
mapper>

④、通过SqlSession对象完成数据的CURD操作

package com.rock.service;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.rock.dao.UserDao;
import com.rock.entities.User;

/**FileName:	com.rock.service 	UserSerivce.java
 * TODO:		
 * Copyright:	Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
 * @author: 	老张
 * @Date:		2019年9月18日:下午2:27:42
 * @version: 	1.0
 * 
 *           Modification History: Date			Author 		Version 	Description
 *           ----------------------------------------------------------------------
 *           					   2019年9月18日 	老张	 		1.0 		1.0 Version
 * 
 */
public class UserSerivce {
	private SqlSession sqlSession=null;
	private UserDao userDao=null;
	@Before
	public void init(){
		try {
			sqlSession=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml")).openSession();
			userDao=sqlSession.getMapper(UserDao.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Test
	public void test_deleteUser(){
		System.out.println(userDao.deleteUser("abc"));
	}
	@Test
	public void test_deleteUserByUser(){
		User user=new User();
		user.setUserid("abc");
		userDao.deleteUserByUser(user);
	}
	@After
	public void commit(){
		sqlSession.commit();
	}
}



  
<mapper namespace="com.rock.dao.UserDao">
	
	<delete id="deleteUser" parameterType="java.lang.String">
		delete from user where userid=#{userid}	
	delete>
	
	<delete id="deleteUserByUser" parameterType="com.rock.entities.User">
		delete from user where userid=#{userid}	
	delete>
	
	<update id="updateUser" parameterType="User">
		update user set password=#{password} where userid=#{userid}
	update>
	
	<insert id="saveUser" parameterType="User">
		insert into user(userid,password,qid,anwser,score) values(#{userid},#{password},#{qid},#{anwser},#{score})
	insert>
	
	<select id="queryById" parameterType="String" resultType="User">
		select * from user where userid=#{userid}
	select>
	
	<select id="queryAll" resultType="User">
		select * from user
	select>
mapper>

4、动态SQL

UserDao.java

package com.rock.mybatis.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;

import com.rock.mybatis.entities.User;

/**FileName:	com.rock.mybatis.dao 	UserDao.java
 * TODO:		
 * Copyright:	Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
 * @author: 	老张
 * @Date:		2019年9月19日:下午2:16:21
 * @version: 	1.0
 * 
 *           Modification History: Date			Author 		Version 	Description
 *           ----------------------------------------------------------------------
 *           					   2019年9月19日 	老张	 		1.0 		1.0 Version
 * 
 */
public interface UserDao {
	public List<User> queryAll();
	public User queryById(String userid);
	public int  updateUser(User user);
	public int  updateUserByIf(User user);
	public List<User> queryAllByQid(String qid);
	public List<User> queryAllByQid2Score(User user);
	public List<User> queryAllBychooseWhenOtherwise(User user);
	public List<User> queryAllByAnwser(String anwser);
	public int  updateUserByTrim(User user);
	public int saveUser(User user);
	public int deleteBatch(String[] ids);
	
	public List<User> queryByMultiCondition(String qid,int score);
	public List<User> queryByMultiConditionParam(@Param("qid1") String qid,@Param("score1")int score);
	public List<User> queryByMultiConditionMap(Map<String,Object> params);
	
}

UserMapper.xml



  
<mapper namespace="com.rock.mybatis.dao.UserDao">
	<resultMap type="com.rock.mybatis.entities.User" id="baseUserMap">
		<id property="userid" column="userid"/>
		<result property="password" column="password"/>
		<result property="qid" column="qid"/>
		<result property="anwser" column="anwser"/>
		<result property="score" column="score"/>
	resultMap>
	
	
	<sql id="BaseUserColumns">
		userid userid,password,qid,anwser,score
	sql>
	<sql id="BaseUserColumns1">
		userid userid,password,qid,anwser,score
	sql>
	
	<select id="queryAll" resultMap="baseUserMap">
		select <include refid="BaseUserColumns"/> from user
	select>
	<select id="queryById" resultMap="baseUserMap" parameterType="String">
		select <include refid="BaseUserColumns1"/> from user where userid=#{userid}
	select>
	<update id="updateUser" parameterType="com.rock.mybatis.entities.User">
		update user set password=#{password},qid=#{qid},anwser=#{anwser},score=#{score} where userid=#{userid}
	update>
	
	<update id="updateUserByIf" parameterType="com.rock.mybatis.entities.User">
		update user set 
		<if test="password !=null">
			password=#{password}
		if>
		
		where userid=#{userid}
	update>
	
	<select id="queryAllByQid" resultMap="baseUserMap" parameterType="String">
		select <include refid="BaseUserColumns"/> from user where qid=#{qid}
	select>
	
	
	<select id="queryAllByQid2Score" resultMap="baseUserMap" parameterType="com.rock.mybatis.entities.User">
		select <include refid="BaseUserColumns"/> 
		from user 
		where 1=1
		<if test="qid!=null">
			and qid=#{qid}	
		if>
		<if test="score!=0"> 
			 and score>#{score}
		if>
	select>
	<select id="queryAllBychooseWhenOtherwise" parameterType="com.rock.mybatis.entities.User" resultMap="baseUserMap">
		select <include refid="BaseUserColumns"/> from user
		where 1=1
		<choose>
			<when test="qid!=null">
				and qid=#{qid}
			when>
			<when test="score!=0">
				and score>#{score}
			when>
			<when test="anwser!=null">
				and anwser=#{anwser}
			when>
			<otherwise>
				and userid=#{userid}
			otherwise>
		choose>
	
	select>
	<select id="queryAllByAnwser" parameterType="String" resultMap="baseUserMap">
		select <include refid="BaseUserColumns"/> from user 
		<where>
				anwser =#{anwser} 
		where>
	select>
	<update id="updateUserByTrim" parameterType="com.rock.mybatis.entities.User">
		update user 
		
		 <trim prefix="set" suffix="where userid=#{userid}" suffixOverrides=",">
		 	<if test="password!=null">
				password=#{password},
		 	if>
		 	<if test="qid!=null">
				qid=#{qid},
		 	if>
		 	<if test="anwser!=null">
				anwser=#{anwser},
		 	if>
		 	<if test="score!=0">
				score=#{score},
		 	if>
		 trim>
	update>
	<insert id="saveUser" parameterType="com.rock.mybatis.entities.User">

		insert into user
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="userid!=null">
				userid,
			if>
			<if test="password!=null">
				password,
			if>
			<if test="qid!=null">
				qid,
			if>
			<if test="anwser!=null">
				anwser,
			if>
			<if test="score!=0">
				score,
			if>
		trim>
		values
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="userid!=null">
				#{userid},
			if>
			<if test="password!=null">
				#{password},
			if>
			<if test="qid!=null">
				#{qid},
			if>
			<if test="anwser!=null">
				#{anwser},
			if>
			<if test="score!=0">
				#{score},
			if>
		trim>
	insert>
	<delete id="deleteBatch" parameterType="String">
		delete from user where userid in
		<foreach collection="array" open="(" close=")" separator="," item="ids">
			#{ids}
		foreach>
	delete>

	<select id="queryByMultiCondition" resultMap="baseUserMap">
		select <include refid="BaseUserColumns"/> from user 
		where
		qid=#{0} and score>#{1}
	select>
	<select id="queryByMultiConditionParam" resultMap="baseUserMap">
		select <include refid="BaseUserColumns"/> from user 
		where
		qid=#{qid1} and score>#{score1}
	select>
	<select id="queryByMultiConditionMap" resultMap="baseUserMap" parameterType="java.util.HashMap">
		select <include refid="BaseUserColumns"/> from user 
		where
		qid=#{qid1} and score>#{score1} and anwser=#{anwser}
	select>
mapper>

UserTest.java

package com.rock.mybatis.entities;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.rock.mybatis.dao.UserDao;

/**FileName:	com.rock.mybatis.entities 	UserTest.java
 * TODO:		
 * Copyright:	Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
 * @author: 	老张
 * @Date:		2019年9月19日:下午2:19:28
 * @version: 	1.0
 * 
 *           Modification History: Date			Author 		Version 	Description
 *           ----------------------------------------------------------------------
 *           					   2019年9月19日 	老张	 		1.0 		1.0 Version
 * 
 */
public class UserTest {
	private UserDao userDao=null;
	@Before
	public void init(){
		try {
			SqlSession sqlSession=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml")).openSession(true);
			userDao=sqlSession.getMapper(UserDao.class);
			System.out.println("UserTest.init() is running.............");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void test_queryAll(){
		List<User> all=userDao.queryAll();
		all.forEach((User user)->System.out.println(user));
	}
	@Test
	public void test_queryById(){
		User user=userDao.queryById("rock");
		System.out.println(user);
	}
	@Test
	public void test_updateUser(){
		User user=new User();
		user.setPassword("123456");
		user.setUserid("admin");
		System.out.println(userDao.updateUser(user));
	}
	@Test
	public void test_updateUserByIf(){
		User user=new User();
		user.setPassword("admin");
		user.setUserid("admin");
		System.out.println(userDao.updateUserByIf(user));
	}
	@Test
	public void test_queryAllByQid(){
		List<User> all=userDao.queryAllByQid("1");
		all.forEach((User user)->System.out.println(user));
	}
	@Test
	public void test_queryAllByQid2Score(){
		User user=new User();
		user.setPassword("admin");
		user.setUserid("admin");
		user.setQid("1");
		user.setScore(100);
		List<User> all=userDao.queryAllByQid2Score(user);
		all.forEach((User u)->System.out.println(u));
	}
	@Test
	public void test_queryAllBychooseWhenOtherwise(){
		User user=new User();
		user.setPassword("admin");
		user.setUserid("admin");
		user.setQid("1");
		user.setScore(100);
		List<User> all=userDao.queryAllBychooseWhenOtherwise(user);
		all.forEach((User u)->System.out.println(u));
	}
	@Test
	public void test_queryAllByAnwser(){
		List<User> all=userDao.queryAllByAnwser("中国");
		all.forEach((User u)->System.out.println(u));
	}
	@Test
	public void test_updateUserByTrim(){
		User user=new User();
		user.setUserid("admin");
		user.setPassword("123456");
		user.setQid("3");
//		user.setScore(600);
		user.setAnwser("中国大连");
		System.out.println(userDao.updateUserByTrim(user));
	}
	@Test
	public void test_saveUser(){
		User user=new User();
		user.setUserid("ccc");
		user.setPassword("123456");
		user.setQid("2");
		user.setScore(300);
//		user.setAnwser("中国大连");
		System.out.println(userDao.saveUser(user));
	}
	@Test
	public void test_deleteBatch(){
		String []ids={"aaa","bbb","ccc"};
		System.out.println(userDao.deleteBatch(ids));
	}
	@Test
	public void test_queryByMultiCondition(){
		List<User> all=userDao.queryByMultiCondition("1",50);
		all.forEach((User user)->System.out.println(user));
	}
	@Test
	public void test_queryByMultiConditionParam(){
		List<User> all=userDao.queryByMultiConditionParam("1",50);
		all.forEach((User user)->System.out.println(user));
	}
	@Test
	public void test_queryByMultiConditionMap(){
		Map<String,Object> params=new HashMap<>();
		params.put("qid1", "1");
		params.put("score1", 10);
		params.put("anwser","中国");
		List<User> all=userDao.queryByMultiConditionMap(params);
		all.forEach((User user)->System.out.println(user));
	}
	@After
	public void after(){
		System.out.println("UserTest.after() is running.......");
	}
}

5、多参数解决方法

①、通过参数索引位置引用 #{0} #{1}…

②、通过Param注解直接为参数定义引用标志 public User login(@Param(“uid”) String userid,@…)

​ MyBatis: #{uid}

​ 少量参数推荐使用的解决方法

③、通过Map存放多条件 将Map中的key作为MyBatis应用的标志

​ 详见如下案例代码

​ 推荐多个参数情况下使用的方法

④、将多个条件封装到Bean中,也是常用的一种解决方法,但是要根据实际需求确定

UserDao.java

package com.ssm.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;

/**FileName:	com.ssm.dao 	UserDao.java
 * TODO:		
 * Copyright:	Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
 * @author: 	老张
 * @Date:		2019年9月20日:上午10:45:22
 * @version: 	1.0
 * 
 *           Modification History: Date			Author 		Version 	Description
 *           ----------------------------------------------------------------------
 *           					   2019年9月20日 	老张	 		1.0 		1.0 Version
 * 
 */
public interface UserDao {
	public User login(String userid,String password);
	public User loginByUser(User user);
	/**
	 * @TODO	 :检索指定qid的且score高于50的所有数据   where qid=#{qid} and score>#{score}
	 * @Date	 :2019年9月20日 上午10:59:32
	 * @Author	 :老张
	 * @param qid
	 * @param score
	 * @return   :
	 */
	public List<User> queryByQidAndScore(@Param("ididid") String qid,@Param("sss") int score);
	/**
	 * @TODO	 :where qid=#{qid} and anwser=#{anwser} and score=#{score}
	 * 			 : Map
	 * 			   map中的元素1:  qidqid :"1"
	 * 			   map中的元素2:  an :"中国"
	 * 			   map中的元素3: s :100
	 * 
	 * 			MyBatis:where qid=#{qidqid} and anwser=#{an} and score=#{s}
	 * @Date	 :2019年9月20日 上午11:09:04
	 * @Author	 :老张
	 * @param params
	 * @return   :
	 */
	public List<User> queryByAidAndAnwserAndScore(Map<String,Object> params);
}

UserMapper.xml



  
<mapper namespace="com.ssm.dao.UserDao">
	<resultMap type="com.ssm.dao.User" id="baseUserMap">
		<id property="userid" column="userid"/>
		<result property="password" column="password"/>
		<result property="qid" column="qid"/>
		<result property="anwser" column="anwser"/>
		<result property="score" column="score"/>
	resultMap>
	
	
	<sql id="BaseUserColumns">
		userid userid,password,qid,anwser,score
	sql>
	
	<select id="loginByUser" resultMap="baseUserMap" parameterType="com.ssm.dao.User">
		select <include refid="BaseUserColumns"/> from user where userid=#{userid} and password=#{password}
	select>
	
	
	<select id="login" resultMap="baseUserMap">
		select <include refid="BaseUserColumns"/> 
		from user where userid=#{0} and password=#{1}
	select>
	
	
	<select id="queryByQidAndScore" resultMap="baseUserMap">
		select <include refid="BaseUserColumns"/> 
		from user where qid=#{ididid} and score>#{sss}
	select>
	
	<select id="queryByAidAndAnwserAndScore" resultMap="baseUserMap" parameterType="hashMap">
		select <include refid="BaseUserColumns"/> 
		from user where qid=#{qidqid} and anwser=#{an} and score=#{s}
	select>
mapper>

UserTest.java

package com.ssm.dao;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

/**FileName:	com.ssm.dao 	UserTest.java
 * TODO:		
 * Copyright:	Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
 * @author: 	老张
 * @Date:		2019年9月20日:上午10:51:02
 * @version: 	1.0
 * 
 *           Modification History: Date			Author 		Version 	Description
 *           ----------------------------------------------------------------------
 *           					   2019年9月20日 	老张	 		1.0 		1.0 Version
 * 
 */
public class UserTest {
	private UserDao userDao=null;
	@Before
	public void init(){
		try {
			SqlSession sqlSession=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml")).openSession(true);
			userDao=sqlSession.getMapper(UserDao.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Test
	public void test_loginByUser(){
		User user=userDao.loginByUser(new User("rock","admin"));
		System.out.println(user);
	}
	@Test
	public void test_login(){
		User user=userDao.login("rock","admin");
		System.out.println(user);
	}
	@Test
	public void test_queryByQidAndScore(){
		List<User> users=userDao.queryByQidAndScore("1",50);
		users.forEach((User user)->System.out.println(user));
	}
	@Test
	public void test_queryByAidAndAnwserAndScore(){
		Map<String,Object> params=new HashMap<>();
		params.put("qidqid","1");
		params.put("an","中国");
		params.put("s",100);
		
		List<User> users=userDao.queryByAidAndAnwserAndScore(params);
		users.forEach((User user)->System.out.println(user));
	}
}

6、MyBatis模糊检索的实现

①、通过字符串拼接方式组装SQL文 不推荐

②、通过在实参中编写模糊检索的通配符方式 推荐

③、通过元素完成 推荐

UserDao.java
	public List<User> queryByLike(@Param("a") String aa);
	public List<User> queryByLike1(@Param("a") String aa);
	public List<User> queryByLike2(User user);

MyBatis配置
<select id="queryByLike" resultMap="baseUserMap" parameterType="String">
		select <include refid="BaseUserColumns"/> 
		from user where 1=1
		<if test="a!=null">
			and userid like #{a}
		</if>
	</select>
	<!-- 
		select * from  user where 1=1 and userid like +"%"+"'"+a的值+"'"+"%";
		注意:
			在MyBatis中 拥有#{}的配置,MyBatis以预处理的方式组装SQL文
			而${}的配置,MyBatis是以字符串拼接的方式组装的SQL文
	 -->
	<select id="queryByLike1" resultMap="baseUserMap" parameterType="String">
		select <include refid="BaseUserColumns"/> 
		from user where 1=1
		<if test="a!=null">
			and userid like '%${a}%'
		</if>
	</select>
	<select id="queryByLike2" resultMap="baseUserMap" parameterType="com.ssm.dao.User">
		<!--
			 bind:将如下变量绑定到当前select配置中。然后就可以在当前配置中通过#{变量名}访问其值了
			 name属性:指定了变量名
			 value属性:指定了这个变量对应的值
			 userid like '%'+r+'%';   
			 _parameter:MyBatis中内置的一个对象,其对应了参数中的那个bean对象  '%r%'
		 -->
		<bind name="likePattern" value="'%'+_parameter.userid+'%'"/>
		select <include refid="BaseUserColumns"/> 
		from user where 1=1
		<if test="userid!=null">
			and userid like #{likePattern}
		</if>
	</select>
	
测试代码:          
@Test
	public void test_queryByLike(){
		List<User> users=userDao.queryByLike("%r%");
		users.forEach((User user)->System.out.println(user));
	}
	@Test
	public void test_queryByLike1(){
		List<User> users=userDao.queryByLike1("r");
		users.forEach((User user)->System.out.println(user));
	}
	@Test
	public void test_queryByLike2(){
		User u=new User();
		u.setUserid("r");
		List<User> users=userDao.queryByLike2(u);
		users.forEach((User user)->System.out.println(user));
	}

7、MyBatis联级检索

①、1:1关系下的联级检索

②、n:1关系下的联级检索

<resultMap type="mybatis.entities.Employee" id="BaseEmployeeMap">
		<id column="empno" property="empno"/>
		<result column="ename" property="ename"/>
		<result column="email" property="email"/>
		<result column="emobile" property="emobile"/>
		<result column="deptno" property="deptno"/>
		<result column="sex" property="sex"/>
		<result column="dname" property="dname"/>
		<result column="location" property="location"/>
		<association property="department" javaType="mybatis.entities.Department"  column="deptno">
			<id column="deptno" property="deptno"/>
			<result column="dname" property="dname"/>
			<result column="location" property="location"/>
		association>
	resultMap>

Emplpoyee.java

public class Employee {
	private String empno;
	private String ename;
	private String email;
	private String emobile;
	private String deptno;
	private String sex;
	private Department department;
}
public class Department {
	private String deptno;
	private String dname;
	private String location;
}

< ②、n:1关系下的联级检索

public class Department {
	private String deptno;
	private String dname;
	private String location;
	private List<Employee> emps;
} 
    public class Employee {
	private String empno;
	private String ename;
	private String email;
	private String emobile;
	private String deptno;
	private String sex;
}
public interface IDepartmentDao {
	public Department queryById(@Param("no") String deptno);
}

<?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">
  <!-- namespace:指明当前mapper需要映射的dao接口的全类名 -->
<mapper namespace="mybatis.dao.IDepartmentDao">
	<resultMap type="mybatis.entities.Department" id="BaseDepartmentMap">
		<id column="deptno" property="deptno"/>
		<result column="dname" property="dname"/>
		<result column="location" property="location"/>
		<!-- 
			collection:设置1:N的联级检索
			property:1一端中定义多一端集合变量名  private List<Employee> emps;
			ofType:多一端的具体类型
			column:关联列
			select:关联其他的<select>
			
		 -->
		<collection property="emps" ofType="mybatis.entities.Employee" column="deptno" select="queryAllEmployeeByDeptno"></collection>
	</resultMap>
	<select id="queryAllEmployeeByDeptno" resultType="mybatis.entities.Employee">
		select * from employee where deptno=#{deptno}
	</select>
	
	<select id="queryById" resultMap="BaseDepartmentMap">
		select * from department where deptno=#{no}
	</select>
</mapper>

8、MyBatis逆向工程




<generatorConfiguration>
  <context id="DB2Tables" targetRuntime="MyBatis3">
  	<commentGenerator>
  		<property name="suppressAllComments" value="true"/>
  	commentGenerator>
  	
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://127.0.0.1:3306/newsystem"
        userId="root"
        password="admin">
    jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    javaTypeResolver>
	
    <javaModelGenerator 
    	targetPackage="mybatis.generater.entities" 
    	targetProject=".\src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    javaModelGenerator>

	
    <sqlMapGenerator 
    	targetPackage="mybatis.generater.dao.mapper"  
    	targetProject=".\src">
      <property name="enableSubPackages" value="true" />
    sqlMapGenerator>

	
    <javaClientGenerator type="XMLMAPPER" 
    	targetPackage="mybatis.generater.dao"  
    	targetProject=".\src">
      <property name="enableSubPackages" value="true" />
    javaClientGenerator>

    <table tableName="news" domainObjectName="News" >table>
    <table tableName="newstype" domainObjectName="NewsType" >table>

  context>
generatorConfiguration>

public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
		 List<String> warnings = new ArrayList<String>();
		   boolean overwrite = true;
		   ConfigurationParser cp = new ConfigurationParser(warnings);
		   Configuration config = cp.parseConfiguration(Test.class.getResourceAsStream("mbg.xml"));
		   DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		   MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		   myBatisGenerator.generate(null);
	}

public class Test {
	public static void main(String[] args) throws IOException {
		NewsMapper newsMapper=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml")).openSession(true).getMapper(NewsMapper.class);
		
		News news=newsMapper.selectByPrimaryKey(174);
		System.out.println(news);
	}
}

log4j.properties


log4j.rootLogger=DEBUG, Console
#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.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

你可能感兴趣的:(SSM(Spring,SpringMVC)