MyBatis学习教程01--创建框架构建、映射文件

1、创建数据库:student

create table student(
	id int (20) PRIMARY key AUTO_INCREMENT,
	name VARCHAR(255),
	city VARCHAR(255),
	age int(5)
	
)

数据库内容:

数据库内容

2、创建项目、导入相关文件

1)在项目文件下创建lib文件夹,导入相关jar包。

2)创建全局配置文件

log4j.xml 用于生成日志信息

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
   <param name="Encoding" value="UTF-8" />
   <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
   </layout>
 </appender>
 <logger name="java.sql">
   <level value="debug" />
 </logger>
 <logger name="org.apache.ibatis">
   <level value="info" />
 </logger>
 <root>
   <level value="debug" />
   <appender-ref ref="STDOUT" />
 </root>
</log4j:configuration>

mybatis-config.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>
  <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://localhost:3306/panda"/><!--建立数据库连接-->
        <property name="username" value="root"/><!--数据库账号-->
        <property name="password" value=""/>
      </dataSource>
    </environment>
  </environments>
  <!-- 将我们写好的sql映射文件(StudentMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
  <mappers>
    <mapper resource="StudentMapper.xml"/>
  </mappers>
</configuration>

创建数据库映射文件

<?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.jc.dao.StudentMapper">
<!-- 
	namespace:名称空间;指定为接口的全类名
	id:唯一标识
	resultType:返回值类型
	#{id}:从传递过来的参数中取出id值
	
 -->

  <select id="getStuById" resultType="com.jc.bean.Student">
    select id,name,city,age from student where id = #{id}
  </select>
</mapper>

创建对应的dao实现文件

StudentMapper.java


package com.jc.dao;

import com.jc.bean.Student;

/**
 * @author JC.Liu
 *
 * 2019年10月8日-下午2:20:13
 */
public interface StudentMapper {
	public Student getStuById(Integer id);
}

3、 创建java Bean文件

创建bean文件时候保证bean对象属性值与表名的字段一一对应,当然如果不对应也可以起别名。

Student.java

/**
 * 
 */
package com.jc.bean;

/**
 * @author JC.Liu
 *
 * 2019年10月8日-下午1:40:00
 */
public class Student {
	private Integer id;
	private String name;
	private String city;
	private Integer age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", city=" + city + ", age=" + age + "]";
	}
	
}

4、创建测试类

StudentTest.java


package com.jc.test;

import java.io.IOException;
import java.io.InputStream;

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

import com.jc.bean.Student;
import com.jc.dao.StudentMapper;
import com.jc.dao.StudentMapperAnnotation;


/**
 * @author JC.Liu
 *
 * 2019年10月8日-下午2:31:37
 */
public class StudentTest {
	//根据xml配置文件,创建一个SqlSessionFactory对象,有数据源进行运行环境信息
	public SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		return new SqlSessionFactoryBuilder().build(inputStream);
	}
	
	//创建一个测试函数
	@Test
	public void test() throws IOException {
		//获取SqlSession实例
		SqlSessionFactory sqlSessionFactory=getSqlSessionFactory();
		SqlSession openSession=sqlSessionFactory.openSession();
		try {
			Student student=openSession.selectOne(
					"com.jc.StudentMapper.selectStu",1);
			System.out.println(student);
		} finally {
			openSession.close();
		}
	}
	
	@Test
	public void test01() throws IOException {
		SqlSessionFactory sqlSessionFactory=getSqlSessionFactory();
		SqlSession openSession=sqlSessionFactory.openSession();
		try {
			StudentMapper mapper=openSession.getMapper(StudentMapper.class);
			Student student=mapper.getStuById(1);
			System.out.println(mapper.getClass());
			System.out.println(student);
		} finally {
			openSession.close();
		}
	}
	
	@Test
	public void test02() throws IOException {
		SqlSessionFactory sqlSessionFactory=getSqlSessionFactory();
		SqlSession openSession=sqlSessionFactory.openSession();
		try {
			StudentMapperAnnotation mapper=openSession.getMapper(StudentMapperAnnotation.class);
			
		} finally {
			openSession.close();
		}
	}
	
	
}

StudentMapperAnnotation.java

package com.jc.dao;

import org.apache.ibatis.annotations.Select;

import com.jc.bean.Student;

/**
 * @author JC.Liu
 *
 * 2019年10月8日-下午3:30:21
 */
public interface StudentMapperAnnotation {
	@Select("select * from student where id=#{id}")
	public Student getStuById(Integer id);
}

运行结果:

发布了78 篇原创文章 · 获赞 5 · 访问量 8297

猜你喜欢

转载自blog.csdn.net/qq_36789311/article/details/102381490