本文章仅为一个Mybatis的Demo示例,操作mapper.xml里面的sql语句的方式有多种,本人比较推崇通过mapper接口的方式来操作,示例如下:
整个工程目录如下:
接下来逐个说明下:
1、Maven工程的核心配置文件 pom.xml 里面配置所有需要引入的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>mybatis.ltcui</groupId>
<artifactId>MybatisHelloWord</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mybatis.version>3.2.8</mybatis.version>
<oracle.driver.version>11.2.0.3.0</oracle.driver.version>
<logback.version>1.1.3</logback.version>
</properties>
<dependencies>
<!-- mybatis start -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis end -->
<!-- db oracle -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>${oracle.driver.version}</version>
</dependency>
<!-- db oracle -->
<!-- logback start -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- logback end -->
</dependencies>
<!-- 指定maven编译方式为jdk1.7版本 -->
<profiles>
<profile>
<id>jdk-1.7</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.7</jdk>
</activation>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.compilerVersion>1.7</maven.compiler.compilerVersion>
</properties>
</profile>
</profiles>
</project>
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配置文件 -->
<properties resource="mybatis-config.properties" />
<typeAliases>
<package name="com.ltcui.student"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 数据库基本信息配置 -->
<property name="driver" value="${connect.oracle.driverClassName}" />
<property name="url" value="${connect.oracle.url}" />
<property name="username" value="${connect.oracle.username}" />
<property name="password" value="${connect.oracle.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 指定引入单个mapper.xml文件 -->
<!-- <mapper resource="com.ltcui.student.dao.studentMapper.xml"/> -->
<!-- 自动查找指定目录下的所有mapper.xml文件 -->
<package name="com.ltcui"/>
</mappers>
</configuration>
用来配置数据库相关信息及其它信息!
3、数据库配置文件 mybatis-config.properties
#连接数据库相关配置 ORACLE 开始####
connect.db=oracle
connect.oracle.url=jdbc:oracle:thin:@//127.0.0.1:1521/orcl
connect.oracle.driverClassName=oracle.jdbc.driver.OracleDriver
connect.oracle.username=123
connect.oracle.password=1234
#连接数据库相关配置 结束####
4、完成以上配置后,下面创建一个获取SqlSessionFactory对象的公用类 MybatisFactoryUtils
文件 MybatisFactoryUtils.java
package com.ltcui;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MybatisFactoryUtils {
private static Logger logger = LoggerFactory.getLogger(MybatisFactoryUtils.class);
private static SqlSessionFactory factory = null;
/**
* 单例模式 获取 SqlSessionFactory 对象
*
* @return
*/
public static SqlSessionFactory getSessionFactory() {
if(MybatisFactoryUtils.factory == null){
synchronized(MybatisFactoryUtils.class){
if(MybatisFactoryUtils.factory == null){
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
MybatisFactoryUtils.factory = new SqlSessionFactoryBuilder().build(inputStream);
}
}
}
logger.info(MybatisFactoryUtils.factory + "");
return MybatisFactoryUtils.factory;
}
}
完成后,写一个测试类来测试下是否成功: MybatisFactoryUtilsTest.java
package com.ltui;
import com.ltcui.MybatisFactoryUtils;
public class MybatisFactoryUtilsTest {
public static void main(String[] args) {
MybatisFactoryUtils.getSessionFactory();
}
}
打印出如下的信息:
则说明环境搭建成功且已经成功连接到数据库
需要说明的是 其中的Oracle的Jar包,在Maven官网库里面没有相应的Jar包供下载,需要自己去网上下载,下载后可以导入自己本地的Maven库中,下面给出导入到本地Maven资源库的一个示例:
mvn install:install-file -Dfile=sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0 -Dpackaging=jar
-- 示例:
mvn install:install-file -Dfile=ojdbc6-11.2.0.3.0.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3.0 -Dpackaging=jar
下面给出一个通过Mapper接口形式操作数据的示例:
1、先创建一个实体类 Student.java
package com.ltcui.student;
public class Student {
private String stuId;
private String stuName;
private String stuSex;
private int stuAge;
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuSex() {
return stuSex;
}
public void setStuSex(String stuSex) {
this.stuSex = stuSex;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
@Override
public String toString() {
return "Student [stuId=" + stuId + ", stuName=" + stuName + ", stuSex=" + stuSex + ", stuAge=" + stuAge + "]";
}
}
2、接着再创建一个Mapper接口类 StudentMapper.java
package com.ltcui.student.dao;
import com.ltcui.student.Student;
public interface StudentMapper {
Student getStudentById(String stuId);
}
3、在StudentMapper.java的目录(也可以在其它目录)里面创建一个 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.ltcui.student.dao.StudentMapper">
<select id="getStudentById" parameterType="string" resultType="Student">
select stuId, stuName, stuSex, stuAge
from student
where stuId = #{stuId}
</select>
</mapper>
内容表示根据学生ID查询一个学生对象
3、创建一个业务处理类 StudentServices.java
package com.ltcui.student.services;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.ltcui.MybatisFactoryUtils;
import com.ltcui.student.Student;
import com.ltcui.student.dao.StudentMapper;
public class StudentServices {
/**
* 根据学生ID查询学生
*
* @param stuId 学生ID
* @return 学生对象
*/
public Student getStudentById(String stuId) {
// 获取 SqlSessionFactory
SqlSessionFactory sqlSessionFalctory = MybatisFactoryUtils.getSessionFactory();
SqlSession sqlSession = sqlSessionFalctory.openSession();
// 此处需要注意 StudentMapper类的路径 需要与 studentMapper.xml配置文件里面的namespace一致 否则会报错误
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); // 获取StudentMapper 接口对象
Student student = studentMapper.getStudentById(stuId); // 直接调用接口
sqlSession.close(); // 注意不要忘记关闭
return student ;
}
}
接着再对该业务类作个测试,写个测试类 MybatisFactoryUtilsTest.java:
package com.ltui.student.services;
import com.ltcui.student.Student;
import com.ltcui.student.services.StudentServices;
public class StudentServicesTest {
public static void testGetStudentById(String stuId){
StudentServices services = new StudentServices();
Student studnet = services.getStudentById(stuId);
System.out.println(studnet.toString());
}
public static void main(String[] args) {
testGetStudentById("1");
}
}
执行结果打印如下:
最后附上Student数据表结构创建语句Oracle
CREATE TABLE student
(
stuId VARCHAR2(20),
stuName VARCHAR2(20),
stuSex VARCHAR2(20),
stuAge INTEGER,
PRIMARY KEY (stuId)
) ;
源代码请参考: MybatisHelloWorld
至此结束,谢谢!
闪出 ... ...