学习MyBatis从零开始_01(基础环境搭建以及基本使用)
2013-07-19 04:08
976 查看
什么是mybatis
MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plan Old Java Objects,普通的Java对象)映射成数据库中的记录。
本教程将以循序渐进的方式讲解Mybatis,最后将以spring+maven+mybatis进行项目搭建
搭建基础环境(通过maven)
1.首先是添加依赖<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <!-- Mybatis 开发包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.1.1</version> </dependency> <!-- Mybatis 和Spring的 整合包,是mybatis出的 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.1</version> </dependency> <!-- mysql的数据库驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <!-- 日志打印 log4j包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> <scope>runtime</scope> </dependency>ps:依赖可能有多余的。。
2.新建mybatis-config.xml,我是在根目录建立的。
目录结构如下,由于本项目要做成web工程所以会有web类的包,但初期没有用到
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 type="com.sin.model.Student" alias="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/student_manager" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/StudentMapper.xml" /> </mappers> </configuration>
这里面主要是设置了别名,添加了数据源,还有告诉mybatis到哪去找到对应的映射文件
3.创建mapper文件
在resources下面的mapper文件夹下创建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.sin.dao.StudentDao"> <insert id="insert" parameterType="Student"> insert into student(name,age,sex,clazz_id) values(#{name},#{age},#{sex},#{clazzId}) </insert> <select id="select" resultType="Student" parameterType="int"> select * from student where id=#{id} </select> </mapper>
Note:这里namespace的值必须与接口名字一样,因为下面要用的是接口映射方式。
parameterType的值是domain类型,由于在上一步中添加了别名(
typeAliases) 所以可以直接使用Student
4.创建实体类以及接口
package com.sin.dao; import com.sin.model.Student; public interface StudentDao { public void insert (Student student); public Student select(int id); }
------------------------------------------------------------------------
package com.sin.model; import java.io.Serializable; public class Student implements Serializable { private Integer id; private String name; private Integer age; private Boolean sex; private Integer clazzId; private static final long serialVersionUID = 1L; 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 Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Boolean getSex() { return sex; } public void setSex(Boolean sex) { this.sex = sex; } public Integer getClazzId() { return clazzId; } public void setClazzId(Integer clazzId) { this.clazzId = clazzId; } }
取得sqlSession的工具类
package com.sin.utils; 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; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; public class SqlMapUtils { private static final Logger logger = LogManager .getLogger(SqlMapUtils.class); private static final String CONFIG_FILE_PATH = "mybatis-config.xml"; private SqlSessionFactory sessionFactory = null; private SqlSession session = null; private static SqlMapUtils instance = null; public SqlMapUtils() { Reader reader = null; try { reader = Resources.getResourceAsReader(CONFIG_FILE_PATH); sessionFactory = new SqlSessionFactoryBuilder().build(reader); session = sessionFactory.openSession(); } catch (IOException e) { // TODO Auto-generated catch block logger.fatal("IO Exception occured while reading the Configuration File \n" + e); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static synchronized SqlMapUtils getInstance() { if (instance == null) { synchronized (SqlMapUtils.class) { instance = new SqlMapUtils(); } } return instance; } public SqlSession getSession() { if (session == null) { throw new RuntimeException("Create SqlSession failed."); } return session; } }
5.测试成果吧
在test目录下新建Stu
4000
dentDaoTest.java
package com.sin.test; import org.apache.ibatis.session.SqlSession; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.sin.dao.StudentDao; import com.sin.model.Student; import com.sin.utils.SqlMapUtils; public class StudentDaoTest { private StudentDao studentDao; private SqlSession sqlSession; @Before public void init() { sqlSession = SqlMapUtils.getInstance().getSession(); studentDao = sqlSession.getMapper(StudentDao.class); } @Test public void testInsert() { Student student = new Student(); student.setAge(11); student.setName("zhangsan"); student.setSex(true); student.setClazzId(1); studentDao.insert(student); sqlSession.commit(); } @Test public void testSelect () { Student student = studentDao.select(1); System.out.println(student.getName()); } @After public void end(){ sqlSession.close(); } }
大功告成!
补充还有一种映射方法,这种并不通过接口,而是使用命名空间和id进行寻找,本质上与上种方法一样的。
package com.sin.test; import org.apache.ibatis.session.SqlSession; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.sin.dao.StudentDao; import com.sin.model.Student; import com.sin.utils.SqlMapUtils; public class StudentDaoTest2 { private SqlSession sqlSession; @Before public void init() { sqlSession = SqlMapUtils.getInstance().getSession(); } @Test public void testInsert() { Student student = new Student(); student.setAge(12); student.setName("lisi"); student.setSex(true); student.setClazzId(1); sqlSession.insert("com.sin.dao.StudentDao.insert", student); sqlSession.commit(); } @Test public void testSelect () { Student student = sqlSession.selectOne("com.sin.dao.StudentDao.select", 1); System.out.println(student.getName()); } @After public void end(){ sqlSession.close(); } }
使用junit来运行
下面是对上面配置文件中一些属性的解释:
1.id是对操作的唯一标识。
2.PrameterTyppe是传入参数的类型
3.ResultType是返回的数据需要转换的类型
4.ResultMap 如果实体类中的属性与数据库中的字段名字不一样可以在这里进行配置。
相关文章推荐
- Mybatis学习笔记一:环境搭建以及简单使用
- Redis学习——环境搭建以及基础命令使用
- 开始hadoop前的准备:ubuntu学习笔记-基本环境的搭建(ssh的安装,SecureCRT连接,vim的安装及使用、jdk的安装)
- solr环境的搭建以及基本的使用方法
- 从零开始学习Extjs5_01搭建环境
- Nutch1.7学习笔记1:基本环境搭建及使用
- Java语言基础{Java_se(01)}-搭建Java开发环境-环境变量(环境配置)-Java的基本语法-Java的三大注释-关键字和保留字-Java中的语言分隔符
- hadoop学习第一天~环境搭建以及初步使用
- 01-Linux基础入门(一)-学习环境的搭建
- Maven基础:Maven环境搭建及基本使用(1)
- unity学习笔记01--基础视图以及基本操作
- 使用python fabric搭建RHEL 7.2大数据基础环境以及部分优化
- hadoop学习1---基础环境搭建与使用
- Nutch1.7学习笔记:基本环境搭建及使用
- 从零开始搭建深度学习服务器: 基础环境配置(Ubuntu + GTX 1080 TI + CUDA + cuDNN)
- kafka学习(一) ---- 基本概念以及环境搭建
- Nutch1.7学习笔记1:基本环境搭建及使用
- OpenGL学习笔记(一):环境搭建、三维空间坐标系理解以及OpenGL的基本使用
- 学习大数据的第一步-搭建Scala开发环境,以及使用Intellij IDEA开发Scala程序
- 从零开始系列--R语言基础学习笔记之一 环境搭建