MyBatis入门

原创 2017年09月15日 19:44:02

项目代码下载

点击下载项目源码(超链接)


项目总体结构


创建数据库,数据表


在项目中创建类

package entity;

public class Student {
	
	private int id;
	private Integer age;
	private Integer score;
	private String name;
	public Student() {		
	}
	public Student(String name,Integer age, Integer score) {
	
		this.age = age;
		this.score = score;
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Integer getScore() {
		return score;
	}
	public void setScore(Integer score) {
		this.score = score;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", age=" + age + ", score=" + score
				+ ", name=" + name + "]";
	}
	

	

}


添加jar,mybatis.xml,db_mysql.properties

mybatis.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="db_mysql.properties"></properties>

	<!-- 设置别名 -->
	<typeAliases>
		<package name="entity"></package>
	</typeAliases>

	<environments default="mysqlEM">

       <!--数据库连接信息,注意上面的default属性和下面的id属性一致 -->
		<environment id="mysqlEM">
			<transactionManager type="JDBC">
			</transactionManager>

			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClass}" />
				<property name="url" value="${jdbc.jdbcUrl}" />
				<property name="username" value="${jdbc.user}" />
				<property name="password" value="${jdbc.password}" />

			</dataSource>
		</environment>
	</environments>
   
   <!-- 引入类接口的xml -->
	<mappers>
		<mapper resource="StudentMapper.xml" />
	</mappers>


</configuration>

db_mysql.properties

jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/text

jdbc.initPoolSize=5
jdbc.maxPoolSize=10
#...


lo4j.properties

log4j.rootLogger=DEBUG, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-5p   %m%n
log4j.logger.org.apache=INFO


创建操作类的接口

package dao;

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

import entity.Student;

public interface IStudentDao {
  
    //将查询对象封装到Student对象中,测试if动态拼接字符串
    List<Student>  selectStudentByIf(Student student);
    
    //测试Where动态拼接字符串
    List<Student>  selectStudentByWhere(Student student);
    
    //测试choose动态拼接字符串
    List<Student>  selectStudentByChoose(Student student);
    
    //测试传入是数组的foreach动态拼接字符串
    List<Student>  selectStudentByForeach(int[]  a);
    
    //测试传入是List的foreach动态拼接字符串
    List<Student>  selectStudentByForeach2(List  a);
    } 


创建对应4中接口的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="dao.IStudentDao">

   <!-- 当表的字段和类的属性不一样时候
   column指向的是表中的字段,property指向的是类中的属性
    <resultMap type="entity.Student" id="StudentResult">
    <id column="tid"  property="id"/>
    <result column="tusername"  property="username"/>
    <result column="tpassword"   property="password"/>   
  </resultMap>
   -->


<select id="selectStudentByIf"  resultType="Student">
  select id,name,score from student where 1 = 1
  <if test="name != null and name != ''">
     and name like '%' #{name} '%'
  </if>
    <if test="age >0">
     and age > #{age}
  </if>
</select>


<select id="selectStudentByWhere"  resultType="Student">
  select id,name,score from student 
  <where>
     <if test="name != null and name != ''">
	   and name like '%' #{name} '%'
    </if>
	<if test="age >0">
		and age > #{age}
	</if>
  </where>
</select>
	
	
	
<select id="selectStudentByChoose"  resultType="Student">
  select id,name,score from student 
  <where>
     <choose>
        <when test=" name !=null and name !='' "> and name like '%' #{name} '%' </when>
         <when test =" age > 0"> and age > #{age}</when>
        <otherwise>and 1 = 2</otherwise>
     </choose>
  </where>
</select>




<select id="selectStudentByForeach"  resultType="Student">
  select id,name,age,score from student 
  <where>
     <if test="array.length > 0">
       id in
       <foreach collection="array"  open="("  close=")"  item="myid" separator=",">
         #{myid}
       </foreach>
     </if>
  </where>
</select>

<select id="selectStudentByForeach2"  resultType="Student">
  select id,name,age,score from student 
  <where>
     <if test="list.size > 0">
       id in
       <foreach collection="list"  open="("  close=")"  item="myid" separator=",">
         #{myid}
       </foreach>
     </if>
  </where>
</select>
</mapper>


测试

工具类,用于获取SqlSession

package until;

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 MyBatisUntil {

	private static SqlSessionFactory sqlSessionFactory;

	public static SqlSession getSqlSession() {
		Reader reader;
		try {
			reader = Resources.getResourceAsReader("mybatis.xml");
			if (sqlSessionFactory == null) {

				sqlSessionFactory = new SqlSessionFactoryBuilder()
						.build(reader);
			}
			SqlSession sqlSession = sqlSessionFactory.openSession();

			return sqlSession;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

}

Main

package text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import until.MyBatisUntil;
import dao.IStudentDao;
import entity.Student;

public class Main {
	
	private IStudentDao dao;
	@Before
	public void before(){
		SqlSession sqlSession=MyBatisUntil.getSqlSession();
		dao=sqlSession.getMapper(IStudentDao.class);
	}
	
	@Test
	public void selectStudentByForeach2(){
        
        List<Integer> a=new ArrayList<Integer>();
        a.add(1);
        a.add(3);
        List<Student> students=dao.selectStudentByForeach2(a);
        for (Student student : students) {
			System.out.println(student);
		}	
	}


}



SpringMVC的HelloWord

SpringMVC入门 搭建SpringMVC环境

Maven中本地仓库,中央镜像,JDK版本配置

Maven镜像配置,Maven中配置JDK版本,Maven配置本地仓库,Maven

mybatis从入门到精通

  • 2017年10月27日 12:04
  • 48.82MB
  • 下载

mybatis入门之二、使用接口interface

2.1 为何使用接口 interface 来编程**上一章用SqlSession实例来直接执行已映射的SQL语句: session.selectOne(“com.yihaomen.mybatis.m...

mybatis 入门文档

  • 2015年09月18日 11:56
  • 200KB
  • 下载

MyBatis3 快速入门

  • 2017年08月24日 22:45
  • 543KB
  • 下载

MyBatis 入门到精通(三) 高级结果映射

MyBatis的创建基于这样一个思想:数据库并不是您想怎样就怎样的。虽然我们希望所有的数据库遵守第三范式或BCNF(修正的第三范式),但它们不是。如果有一个数据库能够完美映射到所有应用程序,也将是非常...

Mybatis入门程序

  • 2017年07月21日 23:17
  • 3.57MB
  • 下载

MyBatis入门详解

  • 2017年07月19日 09:37
  • 2.9MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:MyBatis入门
举报原因:
原因补充:

(最多只允许输入30个字)