Java从入门到入土之mybatis初级篇

Mybatis

  1. Mybatis所需包
    下载地址:https://github.com/mybatis/mybatis-3/releases
    Java从入门到入土之mybatis初级篇_第1张图片
  2. 配置文件
    mybatis-config.xml(名字没有强制要求,一般这样命名)



<configuration>
    
    <properties resource="dataSource.properties"/>
    
    <settings>
    	
        <setting name="logImpl" value="LOG4J" />
    settings>
	
    <typeAliases>
        
        <typeAlias alias="user" type="com.daily.pojo.User">typeAlias>
        
        <package name="com.daily.pojo"/>
    typeAliases>
    
    <typeHandlers>typeHandlers>
    
    <objectFactory type="">objectFactory>
    
    <plugins>
        
        <plugin interceptor="com.github.pagehelper.PageHelper">
            
            <property name="dialect" value="mysql"/>
        plugin>
    plugins>
     
    <environments default="development1">
        
        <environment id="development1">
            
            <transactionManager type="JDBC">transactionManager>
            
             
            <dataSource type="POOLED">
                
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.name}" />
                <property name="password" value="${jdbc.password}" />
            dataSource>
        environment>
        <environment id="development2">
            
            <transactionManager type="JDBC">transactionManager>
            
             
            <dataSource type="POOLED">
                
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
            dataSource>
        environment>
    environments>

    
    <mappers>
        
        <mapper resource="com/mapper/UserMapper.xml"/>
        
        <package name="com.mapper"/>
        
        <mapper class="com.mapper.UserMapper"/>
    mappers>
configuration>

Setting属性详解
typeHandler句柄详解
资源文件
dataSource.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc.url=jdbc:mysql://localhost:3306/数据库名
jdbc.username=root
jdbc.password=root

resultMap




<mapper namespace="com.mapper.StudentMapper">
	
	<resultMap type="com.pojo.Teacher" id="teacher">
		
		<constructor>
			
			<idArg column=""/>
			
			<arg column=""/>
		constructor>
		
		<id column="tid" property="tid" />
		
		<result column="name" property="name" javaType="String" jdbcType="VARCHAR"/>
		
		<association property="" column="" javaType="">association>
		
		<collection property="" column="" ofType="" select="">
		collection>
	resultMap>
mapper>

一个Teacher,Student的demo

pojo实体类
Teacher

package com.pojo;

import java.util.List;

public class Teacher {
	
	private int tid;
	private String name;
	private List<Student> students;
	
	public Teacher() {
		super();
	}

	public Teacher(int tid, String name) {
		super();
		this.tid = tid;
		this.name = name;
	}

	public int getTid() {
		return tid;
	}

	public void setTid(int tid) {
		this.tid = tid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public List<Student> getStudents() {
		return students;
	}

	public void setStudents(List<Student> students) {
		this.students = students;
	}

	@Override
	public String toString() {
		return "Teacher [tid=" + tid + ", name=" + name + ", students=" + students + "]";
	}
}

Student

package com.pojo;

public class Student {

	private int sid;
	private String name;
	private int tid;

	public Student() {
		super();
	}

	public int getsid() {
		return sid;
	}
	public void setsid(int sid) {
		this.sid = sid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getTid() {
		return tid;
	}
	public void setTid(int tid) {
		this.tid = tid;
	}

	@Override
	public String toString() {
		return "Student{" +
				"sid=" + sid +
				", name='" + name + '\'' +
				", tid=" + tid +
				'}';
	}
}

xml映射文件
StudentMapper.xml



<mapper namespace="com.mapper.StudentMapper">
    <resultMap type="com.pojo.Student" id="student">
        <id column="sid" property="sid" />
        <result column="name" property="name" javaType="String" jdbcType="VARCHAR"/>
        <result column="tid" property="tid" />
    resultMap>
    
    <select id="getStudentByTid" resultType="student" parameterType="int">
        select * from student where tid = #{tid}
    select>
mapper>

TeacherMapper.xml



<mapper namespace="com.mapper.TeacherMapper">
<resultMap type="com.pojo.Teacher" id="teacher">
	<id column="tid" property="tid"/>
	<result column="name" property="name"/>
	
	<collection property="students" column="tid" ofType="list" select="com.mapper.StudentMapper.getStudentByTid">
		
		<id column="sid" property="sid"/>
		<result column="name" property="name"/>
		<result column="tid" property="tid"/>
	collection>
resultMap>
<select id="getByTid" parameterType="int" resultMap="teacher">
	select * from teacher where tid = #{tid}
select>
mapper>

dao层接口
StudentMapper

public interface StudentMapper {

	List<Student> getStudentByTid(int tid);
}

TeacherMapper

public interface TeacherMapper {

	Teacher getByTid(int Tid);
}

测试类

public class Test1 {

    public static void main(String[] args) throws IOException {
        /*获取配置文件mybatis-config.xml*/
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        /*建造会话工厂SqlSessionFactory*/
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        /*生产SqlSession*/
        SqlSession session = sessionFactory.openSession();
        /*通过反射获取TeacherMapper*/
        TeacherMapper mapper = session.getMapper(TeacherMapper.class);
        /*调用TeacherMapper的方法*/
        Teacher teacher = mapper.getByTid(1);
        System.out.println(teacher);
    }
}

运行结果
这里的警告是没有Log4j的配置文件

log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Teacher [tid=1, name=李四, students=[Student{sid=1, name='张三', tid=1}, Student{sid=2, name='赵武', tid=1}]]

Process finished with exit code 0

不适用接口绑定直接调用xml 测试类

public class Test2 {

    public static void main(String[] args) throws IOException {
        /*获取配置文件mybatis-config.xml*/
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        /*建造会话工厂SqlSessionFactory*/
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        /*生产SqlSession*/
        SqlSession session = sessionFactory.openSession();
        /*通过SqlSession调用sql语句,第一个参数为mapper.xml里的方法,第二个参数为方法需要的参数*/
        Teacher teacher = session.selectOne("com.mapper.TeacherMapper.getByTid", 1);
        System.out.println(teacher);
    }
}

运行结果

log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Teacher [tid=1, name=李四, students=[Student{sid=1, name='张三', tid=1}, Student{sid=2, name='赵武', tid=1}]]

Process finished with exit code 0

Log4j配置文件log4j.pproperties(名称确定,不区分大小写)

log4j.rootLogger = error,console

log4j.logger.com.mapper=debug
log4j.logger.org.apache=error
log4j.logger.java.sql.Statement=error
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug

log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern =  %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

运行结果
过滤了大部分无用信息,只留下error和sql相关信息

2019-07-24 14:05:10  [ main:0 ] - [ DEBUG ]  ==>  Preparing: select * from teacher where tid = ? 
2019-07-24 14:05:10  [ main:52 ] - [ DEBUG ]  ==> Parameters: 1(Integer)
2019-07-24 14:05:10  [ main:101 ] - [ DEBUG ]  ====>  Preparing: select * from student where tid = ? 
2019-07-24 14:05:10  [ main:101 ] - [ DEBUG ]  ====> Parameters: 1(Integer)
2019-07-24 14:05:10  [ main:103 ] - [ DEBUG ]  <====      Total: 2
2019-07-24 14:05:10  [ main:103 ] - [ DEBUG ]  <==      Total: 1
Teacher [tid=1, name=李四, students=[Student{sid=1, name='张三', tid=1}, Student{sid=2, name='赵武', tid=1}]]

Process finished with exit code 0

你可能感兴趣的:(mybatis)