开启MyBatis(二)创建工程
来源:互联网 发布:mac 编译android源码 编辑:程序博客网 时间:2024/05/22 00:29
1.说明
在本节的学习中,笔者将会带领读者使用maven来创建项目,当然你也可以使用Gradle,这些都是架包的管理,关于这些工具是如何使用,笔者在这里就不给出了,读者可以自己去网上查找。同时笔者版本管理是用Git,读者也可以研究如何使用。所以笔者的源码都放在了GitHub上了,后续笔者会告诉你下载的地址。
2.创建STUDENTS表
下面是创建表的SQL语句:
CREATE TABLE STUDENTS(stud_id int(11) NOT NULL AUTO_INCREMENT,name varchar(50) NOT NULL,email varchar(50) NOT NULL,dob date DEFAULT NULL,PRIMARY KEY (stud_id)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;/*Sample Data for the students table */insert into students(stud_id,name,email,dob)values (1,'Student1','student1@gmail.com','1983-06-25');insert into students(stud_id,name,email,dob)values (2,'Student2','student2@gmail.com','1983-06-25');
3.创建Java的工程
下面我们一起创建Java工程和配置MyBatis的依赖架包。
1) 创建一个Java和工程,名字叫mybatis.com
2) 只要你电脑安装了maven之后,你就可以New|Maven|Maven Project
3) 点击Next时,记得勾选Create a simple project(skip archetype selection).
4) New Maven project,填写信息
5) 将生成的pom.xml的文件,添加junit-4.11.jar、mysql-connectoer-java-5.1.22.jar等的依赖架包。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.owen.mybatis</groupId> <artifactId>mybatis-parent</artifactId> <version>0.0.1</version> <name>mybatis-parent</name> <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.6</java.version><junit.version>4.11</junit.version><slf4j.version>1.7.5</slf4j.version><log4j.version>1.2.17</log4j.version><mybatis.version>3.2.2</mybatis.version><mysql.version>5.1.21</mysql.version><maven.compiler.plugin>2.3.2</maven.compiler.plugin></properties><build><finalName>${project.artifactId}</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>${maven.compiler.plugin}</version><configuration><source>${java.version}</source><target>${java.version}</target><encoding>${project.build.sourceEncoding}</encoding></configuration></plugin></plugins></build><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><scope>test</scope></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>${slf4j.version}</version><scope>runtime</scope></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>${log4j.version}</version><scope>runtime</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version><scope>runtime</scope></dependency></dependencies> </project>
6) 创建 log4j.properties的文件和放到src/main/resources的目录下
log4j.rootLogger=INFO, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%nlog4j.logger.com.owen.mybatis=DEBUG
4. 创建mybatis-config.xml和Student Mapper.xml的配置文件
让我们创建MyBatis的主要的配置文件mybatis-config.xml,这个包含了数据库的连接,加载的对象别名等。当然,我们的数据库加载的信息将会配置到另外一份的文件中。还有StudentMapper.xml的文件,包含了SQL的声明。
1) 创建一个文件appliation.properties的文件,里面包含了数据库连接和信息。
################### DataSource Configuration ##########################jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatisjdbc.username=rootjdbc.password=root
2) 创建一个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> <properties resource="application.properties"/> <typeAliases> <package name="com.owen.mybatis.domain"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/owen/mybatis/mappers/StudentMapper.xml"/> </mappers> </configuration>
3) 创建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.owen.mybatis.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=#{studId} </select> <insert id="insertStudent" parameterType="Student"> INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob}) </insert> <update id="updateStudent" parameterType="Student"> UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId} </update> </mapper>
5. 创建单例类:MyBatisSqlSessionFactory
package com.owen.mybatis.util;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.util.Properties;import org.apache.ibatis.datasource.DataSourceFactory;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;/** * 与数据库连接的JDBC层 * @author OwenWilliam 2016-6-18 * @since * @version v1.0.0 * */public class MyBatisSqlSessionFactory{ private static SqlSessionFactory sqlSessionFactory;private static final Properties PROPERTIES = new Properties();static{try {//获取数据库连接信息InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");PROPERTIES.load(is);} catch (IOException e) {e.printStackTrace();}}/** * 使用单例模式操作 * @return */public static SqlSessionFactory getSqlSessionFactory(){if(sqlSessionFactory==null) {InputStream inputStream = null;try{//获取配置文件信息inputStream = Resources.getResourceAsStream("mybatis-config.xml");//将信息放到容器中sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}catch (IOException e){throw new RuntimeException(e.getCause());}finally {if(inputStream != null){try {inputStream.close();} catch (IOException e) {}}}}return sqlSessionFactory;}public static SqlSession getSqlSession() {return getSqlSessionFactory().openSession();}/** * 数据库连接,这个只是测试中应用 * @return */public static Connection getConnection() {String driver = PROPERTIES.getProperty("jdbc.driverClassName");String url = PROPERTIES.getProperty("jdbc.url");String username = PROPERTIES.getProperty("jdbc.username");String password = PROPERTIES.getProperty("jdbc.password");Connection connection = null;try {Class.forName(driver);connection = DriverManager.getConnection(url, username, password);} catch (Exception e) {throw new RuntimeException(e);} return connection;}}
6.创建StudentMapper接口和StudentService类
我们将创建一个StudentMapper的接口,接口中定义的就是要与映射文件StudentMapper,xml中配置的id要保持一样,同时我们创建个StudentService的类,来继承StudentMapper的接口。
1) StudentMapper的接口类。
package com.owen.mybatis.mappers;import java.util.List;import com.owen.mybatis.domain.Student;/** * 服务层操作 Strudent 接口 * 与StudentMapper.xml中SQL的id要对应上 * 查找所:StudentResult * 查找个体:Student * 参数也要对应xml中的id * @author OwenWilliam 2016-6-18 * @since * @version v1.0.0 * */public interface StudentMapper{/** * 查找所有有Student * @return */List<Student> findAllStudents();/** * 通过ID号查找Student * @param id * @return */Student findStudentById(Integer id);/** * 插入新的Student * @param student */void insertStudent(Student student);/** * 更新Student * @param student */void updateStudent(Student student);}
2) 创建StudentService的类要继承StudentMapper的接口。
package com.owen.mybatis.services;import java.util.List;import org.apache.ibatis.session.SqlSession;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.owen.mybatis.domain.Student;import com.owen.mybatis.mappers.StudentMapper;import com.owen.mybatis.util.MyBatisSqlSessionFactory;/** * Student的业务 层操作,具体操作 * @author OwenWilliam 2016-6-18 * @since * @version v1.0.0 * */public class StudentService{private Logger logger = LoggerFactory.getLogger(getClass());/** * 查找所有的Student * @return */public List<Student> findAllStudents(){SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();try {//获得Student的映射StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);return studentMapper.findAllStudents();} finally {sqlSession.close();}}/** * 通过ID号查找Student * @param studId * @return */public Student findStudentById(Integer studId){logger.debug("Select Student By ID :{}", studId);SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();try {StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);return studentMapper.findStudentById(studId);} finally {sqlSession.close();}}/** * 创建Student * @param student */public void createStudent(Student student){SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();try {StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);studentMapper.insertStudent(student);sqlSession.commit();} finally {sqlSession.close();}}/** * 更新Student * @param student */public void updateStudent(Student student){SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();try {StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);studentMapper.updateStudent(student);sqlSession.commit();} finally {sqlSession.close();}}}
7. 创建JUnit测试类
下面我们创建一个StudentServiceTest.java的测试类,用来测试StudentService的方法。
package com.owen.mybatis.services;import java.util.Date;import java.util.List;import org.junit.AfterClass;import static org.junit.Assert.*;import org.junit.BeforeClass;import org.junit.Test;import com.owen.mybatis.domain.Student;/** * 测试类 * @author OwenWilliam 2016-6-18 * @since * @version v1.0.0 * */public class StudentServiceTest {private static StudentService studentService;@BeforeClasspublic static void setup(){studentService = new StudentService();TestDataPopulator.initDatabase();}@AfterClasspublic static void teardown(){studentService = null;}@Test public void testFindAllStudents() {List<Student> students = studentService.findAllStudents();assertNotNull(students);for (Student student : students){assertNotNull(student);//System.out.println(student);}}@Test public void testFindStudentById() {Student student = studentService.findStudentById(1);assertNotNull(student);}@Testpublic void testCreateUStudent() {Student student = new Student();int id = 4;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);assertNotNull(newStudent);assertEquals("student_"+id, newStudent.getName());assertEquals("student_"+id+"gmail.com", newStudent.getEmail());}@Testpublic void testUpdateStudent() {int id = 2;Student student =studentService.findStudentById(id);student.setStudId(id);student.setName("student_"+id);student.setEmail("student_"+id+"gmail.com");Date now = new Date();student.setDob(now);studentService.updateStudent(student);Student updatedStudent = studentService.findStudentById(id);assertNotNull(updatedStudent);assertEquals("student_"+id, updatedStudent.getName());assertEquals("student_"+id+"gmail.com", updatedStudent.getEmail());}}
- 开启MyBatis(二)创建工程
- 二、创建Django工程
- git学习二 创建工程
- (二)maven工程创建
- IntelliJ IDEA 创建第一个Mybatis工程
- mybatis逆向工程的创建和使用
- Mybatis的逆向工程(二)
- 二.Cocos2d-x创建HelloWorld工程
- 【Android Studio(二)】创建工程
- cocos2d-js学习笔记<二> 创建工程
- maven工程的创建(二)
- Mybatis(二)-创建第一个应用
- Mybatis源码(二)之Spring整合mybatis创建SqlSession
- Eclipse创建WEB工程Maven+Spring+SpringMVC+MyBatis示例
- 使用mybatis的逆向工程(xml方式)创建java代码
- spring+springMVC+mybatis +dubbo架构的工程创建(一)
- IDEA中使用maven创建mybatis的逆向工程
- IDEA2016创建SpringMVC+MyBatis工程(Maven)所遇到的坑
- Objective-C之Block剖析
- sql 分组查询效率
- template classes or function
- 一句SQL,判断char列的值是否组成回文字符串
- jsonp跨域问题
- 开启MyBatis(二)创建工程
- PAT乙级练习题B1031. 查验身份证
- rdd的join使用
- 你的android应用其实不需要那么多的权限(I don't need your permission!)
- Linux命令详解:cat、more、less命令 结合grep 基本可以查看所有的文件
- java中PreparedStatement接口及ResultSet结果集
- 第3章 关于 Greenplum 中的并发控制
- windows下安装JDK和Tomcat
- nodejs的module.exports 与 exports