MyBatis(3.2.3) - hello world
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis(3.2.3) - hello world相关的知识,希望对你有一定的参考价值。
1. 创建数据表(mysql):
DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `did` int(10) unsigned NOT NULL AUTO_INCREMENT, `dept_name` varchar(127) DEFAULT NULL, `address` varchar(127) DEFAULT NULL, `tel` varchar(16) DEFAULT NULL, PRIMARY KEY (`did`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. 新建 Maven 工程,配置 Maven 依赖:
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.22</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.14.4</version> </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> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> </dependency> </dependencies>
3. JavaBean:
package com.huey.hello.mybatis.beans; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Department { private int did; private String deptName; private String address; private String tel; }
3. Mapper 接口:
package com.huey.hello.mybatis.mapper; import com.huey.hello.mybatis.beans.Department; public interface DepartmentMapper { public int insertDepartment(Department department); public Department getDepartmentById(int did); }
4. 配置映射文件:
<?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"> <!--注意:此处的命名空间是 DepartmentMapper 的全限定类名--> <mapper namespace="com.huey.hello.mybatis.mapper.DepartmentMapper"> <!-- ResultMaps 被用来将 SQL SELECT 语句的结果集映射到 JavaBean 的属性中 --> <resultMap type="Department" id="deptMap"> <!-- 映射主键 --> <id property="did" column="did" /> <!-- 映射普通字段 --> <result property="deptName" column="dept_name"/> <result property="address" column="address"/> <result property="tel" column="tel"/> </resultMap> <!-- 添加部门记录 --> <!-- id 名称需要与 DepartmentMapper 中的方法签名一致 --> <!-- Department 这一别名在 mybatis-config.xml 中配置 --> <insert id="insertDepartment" parameterType="Department"> insert into department(did, dept_name, address, tel) values(#{did}, #{deptName}, #{address}, #{tel}) </insert> <!-- 根据 ID 查询部门记录 --> <select id="getDepartmentById" parameterType="int" resultMap="deptMap"> select * from department where did=#{did} </select> </mapper>
5. 配置 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.huey.hello.mybatis.beans.Department" alias="Department" /> </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/mybatis" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <!-- mapper 对应的 xml 配置文件 --> <mappers> <mapper resource="com/huey/hello/mybatis/mapper/DepartmentMapper.xml" /> </mappers> </configuration>
6. 创建 SqlSessionFactory 单例类:
package com.huey.hello.mybatis.utils; 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; /** * 加载 mybatis-config.xml,创建 SqlSessionFactory 实例 * 每个数据库环境应该就只有一个 SqlSessionFactory 对象实例 * 所以使用单例模式只创建一个 SqlSessionFactory 实例 * @return */ public synchronized 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 openSqlSession() { return getSqlSessionFactory().openSession(); } }
7. 业务逻辑:
package com.huey.hello.mybatis.serv; import org.apache.ibatis.session.SqlSession; import com.huey.hello.mybatis.beans.Department; import com.huey.hello.mybatis.mapper.DepartmentMapper; import com.huey.hello.mybatis.utils.MyBatisSqlSessionFactory; public class DepartmentService { public int createDepartment(Department department) { int result = 0; /** * SqlSession 对象实例不是线程安全的,并且不被共享。 * 每一个线程应该有它自己的 SqlSession 实例。 * 所以 SqlSession 的作用域最好就是其所在方法的作用域。 * 从 Web 应用程序角度上看,SqlSession 应该存在于 request 级别作用域上。 */ SqlSession sqlSession = MyBatisSqlSessionFactory.openSqlSession(); try { DepartmentMapper deptMapper = sqlSession.getMapper(DepartmentMapper.class); result = deptMapper.insertDepartment(department); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } return result; } public Department getDepartmentById(int did) { Department department = null; SqlSession sqlSession = MyBatisSqlSessionFactory.openSqlSession(); try { DepartmentMapper deptMapper = sqlSession.getMapper(DepartmentMapper.class); department = deptMapper.getDepartmentById(did); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } return department; } }
8. 单元测试:
package com.huey.hello.mybatis.serv; import org.junit.Test; import com.huey.hello.mybatis.beans.Department; public class DepartmentServiceTest { DepartmentService deptService = new DepartmentService(); @Test public void testCreateDepartment() { Department department = new Department(1001, "研发部", "XX 路 YY 号", "010-55551234"); deptService.createDepartment(department); } @Test public void testGetDepartmentById() throws Exception { int did = 1001; Department department = deptService.getDepartmentById(did); if (department != null) { System.out.println(department); } } }
以上是关于MyBatis(3.2.3) - hello world的主要内容,如果未能解决你的问题,请参考以下文章
MyBatis(3.2.3) - Configuring MyBatis using XML, Properties