MyBatis初学

MyBatis 初学笔记

Student.java

package com.xjh.domain;

import java.util.Date;

public class Student {

	private Integer studId;
	private String name;
	private String email;
	private Date dob;

	public Integer getStudId() {
		return studId;
	}
	public void setStudId(Integer studId) {
		this.studId = studId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Date getDob() {
		return dob;
	}
	public void setDob(Date dob) {
		this.dob = dob;
	}
}

StudentMapper.java

package com.xjh.mappers;

import java.util.List;

import org.apache.ibatis.session.RowBounds;

import com.xjh.domain.Student;

public interface StudentMapper {

    List<Student> findAllStudents();

    List<Student> findAllStudents(RowBounds rowBounds);

    Student findStudentById(Integer id);

    void insertStudent(Student student);

    int deleteAllStudents();

    int countAllStudents();

}

StudentMapper.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="com.xjh.mappers.StudentMapper">

<resultMap type="Student" id="StudentResult">
	<id property="studId" column="stud_id"/>
	<result property="name" column="name"/>
	<result property="email" column="email"/>
	<result property="dob" column="dob"/>
</resultMap>

<select id="findAllStudents" resultMap="StudentResult">
	select * from students
</select>

<select id="findStudentById" parameterType="int" resultType="Student">
	select stud_id as studid, name, email, dob
	from students where stud_id=#{Id}
</select>

<insert id="insertStudent" parameterType="Student">
	insert into students(stud_id, name, email, dob)
	values(#{studId }, #{name}, #{email}, #{dob})
</insert>

<delete id="deleteAllStudents" parameterType="int">
	delete from students
</delete>

<select id="countAllStudents" resultType="int">
	select count(*) from students
</select>

</mapper>

StudentService.java

package com.xjh.services;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xjh.domain.Student;
import com.xjh.mappers.StudentMapper;
import com.xjh.util.MyBatisSqlSessionFactory;

public class StudentService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	public List<Student> findAllStudents() {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findAllStudents();
		} finally {
			sqlSession.close();
		}
	}

	/**
	 * 采用分页的方式来查询
	 */
	public List<Student> findAllStudents2() {
		int offset = 0, limit = 10;
		RowBounds rowBounds = new RowBounds(offset, limit);
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findAllStudents(rowBounds);
		} finally {
			sqlSession.close();
		}
	}

	public Student findStudentById(Integer studId) {
		logger.debug("Select Student By ID: {}", studId);
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findStudentById(studId);
		} finally {
			sqlSession.close();
		}
	}

	public Student findStudentById2(Integer studId) {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			Student student = (Student) sqlSession.selectOne("com.xjh.mappers.StudentMapper.findStudentById",
					studId);
			return student;
		} finally {
			sqlSession.close();
		}
	}

	public void createStudent(Student student) {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			studentMapper.insertStudent(student);
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
	}

	public int deleteAllStudents() {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			int i = studentMapper.deleteAllStudents();
			sqlSession.commit();
			return i;
		} finally {
			sqlSession.close();
		}
	}

	public int countAllStudents() {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			int i = studentMapper.countAllStudents();
			return i;
		} finally {
			sqlSession.close();
		}
	}

}

StudentServiceTest.java

package com.xjh.services;

import java.util.Date;
import java.util.List;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.xjh.domain.Student;

public class StudentServiceTest {

	private static StudentService studentService;

	@BeforeClass
	public static void setup() {
		studentService = new StudentService();
	}

	@AfterClass
	public static void teardown() {
		studentService = null;
	}

	@Test
	public void testCreateStudent() {
		for (int i = 1; i <= 100; i++) {
			Student student = new Student();
			int id = i;
			student.setStudId(id);
			student.setName("student_" + id);
			student.setEmail("student_" + id + "@gmail.com");
			student.setDob(new Date());
			studentService.createStudent(student);
			Student newStudent = studentService.findStudentById(id);
			Assert.assertNotNull(newStudent);
		}
	}

	@Test
	public void testFindAllStudents() {
		List<Student> students = studentService.findAllStudents();
		Assert.assertNotNull(students);
		for (Student student : students) {
			System.out.println(student);
		}
	}

	@Test
	public void testFindAllStudents2() {
		List<Student> students = studentService.findAllStudents2();
		Assert.assertNotNull(students);
		for (Student student : students) {
			System.out.println("......" + student.getName());
		}
	}

	@Test
	public void testFindStudentById() {
		Student student = studentService.findStudentById(1);
		Assert.assertNotNull(student);
		System.out.println(student);
	}

	@Test
	public void testFindStudentById2() {
		Student student = studentService.findStudentById2(1);
		Assert.assertNotNull(student);
		System.out.println(student);
	}

	@Test
	public void testDeleteAllStudents() {
		int begin = studentService.countAllStudents();
		int end = studentService.deleteAllStudents();
		Assert.assertEquals(end, begin);
		System.out.println("begin: " + begin + " end: " + end);
	}

//	create table students(stud_id int(11) not null auto_increment, name varch
//			ar(50) not null, email varchar(50) not null, dob date default null, primary key
//			(stud_id));

}

MyBatisSqlSessionFactory.java

package com.xjh.util;

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;

public class MyBatisSqlSessionFactory {

	private static SqlSessionFactory sqlSessionFactory;

	public static SqlSessionFactory getSqlSessionFactory() {
		if (sqlSessionFactory == null) {
			InputStream inputStream;
			try {
				inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			} catch (IOException e) {
				throw new RuntimeException(e.getCause());
			}
		}
		return sqlSessionFactory;
	}

	public static SqlSession openSession() {
		return getSqlSessionFactory().openSession();
	}
}

MyBatisUtil.java

package com.xjh.util;

import org.apache.ibatis.session.SqlSession;

public class MyBatisUtil {

	public static SqlSession openSession() {

		return MyBatisSqlSessionFactory.openSession();

	}

}

log4j.properties

log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n

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>
<typeAliases>
<typeAlias alias="Student" type="com.xjh.domain.Student"/></typeAliases>
<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/test"/>
            <property name="username" value="root"/>
            <property name="password" value="123456abcd"/>
        </dataSource>
    </environment>
</environments>
<mappers>
    <mapper resource="com/xjh/mappers/StudentMapper.xml"/>
</mappers>
</configuration>

需要引入的包

<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>

数据库建表语句

create table students(stud_id int(11) not null auto_increment, name varch
            ar(50) not null, email varchar(50) not null, dob date default null, primary key
            (stud_id));
时间: 2024-10-28 23:09:44

MyBatis初学的相关文章

MyBatis初学笔记

1.在SqlMapConfig.xml中配置数据链接池,使用连接池管理数据库链接 1 <!-- 加载属性文件 --> 2 <properties resource="db.properties"> 3 <!--properties中还可以配置一些属性名和属性值 --> 4 <!-- <property name="jdbc.driver" value=""/> --> 5 </pr

初学Java9:学习Mybatis时报错:Parameter &#39;name&#39; not found. Available parameters are [1, 0, param1, param2]

报错-->Parameter 'name' not found. Available parameters are [1, 0, param1, param2] 百度找到这篇文章完成修改 http://blog.csdn.net/w86440044/article/details/29363067 我之前写的操作类是和博主一样,是这样的: 1 // 登录·查询 2 @Select("select * from t_users where uname=#{name} and pswd=#{p

初学MyBatis.net

1.MyBatis.net介绍 MyBatis..net是一个简单,但是完整的ORM框架,它使你的实体对象与sql语句或者存储过程之间的映射变得很简单,并提供数据访问. 2.MyBatis.net配置 主要的配置文件 providers.config:用来定义框架中用到的数据库引擎. SqlMap.config:数据库连接信息,数据映射xml文件信息,设置信息 Default locations for the sqlMap.config and providers.config files W

关于mybatis Invalid bound statement (not found) 问题

初学mybatis   现在系统是spring + mybatis  applicationContext.xml里面配置了Mapper 自动扫描 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    <property name="basePackage" value="com.yolly.platform.*" /></bean&g

MyBatis源码解读(3)——MapperMethod

在前面两篇的MyBatis源码解读中,我们一路跟踪到了MapperProxy,知道了尽管是使用了动态代理技术使得我们能直接使用接口方法.为巩固加深动态代理,我们不妨再来回忆一遍何为动态代理. 我相信在初学MyBatis的时候几乎每个人都会发出一个疑问,为什么明明是XXXDao接口,我没有用任何代码实现这个接口,但却能直接使用这个接口的方法.现在清楚了,动态代理.我们来写一个demo小程序来看看. 首先是一个Test.java的接口,只有一个say方法. 1 package day_16_prox

Spring MVC 学习总结(六)——Spring+Spring MVC+MyBatis框架集成

目录 一.新建一个基于Maven的Web项目    二.创建数据库与表    三.添加依赖包    四.新建POJO实体层    五.新建MyBatis SQL映射层    六.JUnit测试数据访问    七.完成Spring整合MyBatis配置    八.配置web.xml加载Spring容器与MVC    九.创建服务层     十.完成商品管理功能    10.1.商品列表与分页    11.2.删除与多删除功能    11.3.新增商品功能    11.4.编辑商品功能    11.

SSM框架搭建web服务器实现登录功能(Spring+SpringMVC+Mybatis)

初学java EE,虽然知道使用框架会使开发更加便捷高效,但是对于初学者来说,感到使用框架比较迷惑,尤其是各种jar包的引用.各种框架的配置.注解的使用等等. 最好的学习方法就是实践,于是下载了一个现成的DEMO,通过简单的修改先成功在自己电脑上跑起来,然后再逐个文件进行分析学习,最终才能从总体的高度上掌握框架的运行机制和配置方法,这样才能在实际运用中灵活配置,不会再局限于示例框架中. SSM框架搭建流程 SSM框架Web程序的流程 上面链接总结的流程很好,但是该流程没有加入DAO这一层,经过分

mybatis generator配置生成代码的问题

接触第二种orm两天下来,一脸懵逼.mybatis是大多数公司所推崇的,相比于hibernate性能较为好的,操作更为方便的轻量级工具,所以小富就搞起这个orm.好吧,都说mybatis有个配置可以自动生成相应的mapper,bean,dao文件.所以要先到myeclipse中配置一下generator的配置: 1.generator配置: 下载插件地址,根据目录找到这两个文件,放到myeclpse安装目录下 ------> 重启myeclipse后,输入mybatis就可以找到要生成的gene

Spring整合Mybatis的注意事项

初学 Spring 整合 Mybatis,虽然网贴无数,但是每次试行下来,总会发生这样那样的问题.最终经过数天的不断尝试,总算是成功运行了,遇到的多数坑也一一绕过,特此记录已备查: 一.关于依赖包 网上的很多帖子杂七杂八加入了各种依赖包,有时看的人头晕脑胀,经过实测,实际需要的依赖包,只有下面三组: <!-- 1.基础Spring依赖 --> <dependency> <groupId>org.springframework</groupId> <ar