Mybatis的簡單使用步驟(java專案)
阿新 • • 發佈:2018-12-11
1、在eclipse中建立mavenjava專案(jar),並初始化依賴,放入log4j的配置檔案
pom檔案如下(一個是Mybatis必須的,一個是log4j的日誌)
<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.iflytek</groupId> <artifactId>Mybatis1</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
放入log4j的配置檔案(log4j.properties)
# Global logging configuration log4j.rootLogger=ERROR, stdout # MyBatis logging configuration... log4j.logger.com.iflytek=TRACE # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
2、建立mybatis-config.xml檔案,指定最基本的environments和mappers,這裡我用外部載入資料庫配置檔案jdbc.properties
jdbc.properties如下
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver jdbc.url=jdbc:oracle:thin:@172.16.130.35:1521:orcl jdbc.username=uuid jdbc.password=uuid hibernate.dialect=org.hibernate.dialect.Oracle10gDialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=true
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="jdbc.properties" />
<!-- 設定整個包下的檔案都以自己的類名為別名 ,不然在之後的mapper.xml中要寫類的全路徑-->
<typeAliases>
<package name="com.iflytek.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>
<!-- 將對映的檔案指定到類中而不是資原始檔中,可用resource 或者class指定到資原始檔中 -->
<mappers>
<package name="com.iflytek.dao"/>
</mappers>
</configuration>
3、建立對應的pojo, mapper.xml檔案和對應在dao中的介面,這裡用Blog.java, BlogMapper.xml和BlogMapper.java三個檔案
Blog.java
package com.iflytek.domain;
public class Blog {
private int id;
private String title;
private String auth;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuth() {
return auth;
}
public void setAuth(String auth) {
this.auth = auth;
}
@Override
public String toString() {
return "Blog [id=" + id + ", title=" + title + ", auth=" + auth + "]";
}
}
BlogMapper.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.iflytek.dao.BlogMapper">
<!-- 當資料庫的欄位與pojo的欄位不匹配時,要指定resultMap,下面指定resultMap 而不是resultType column為資料庫的,property為pojo的 -->
<resultMap type="Blog" id="bid">
<id column="id" property="id" />
<result column="title1" property="title" />
<result column="auth1" property="auth" />
</resultMap>
<!--select,insert,update,delete四個標籤定義sql語句,每一個標籤對應一條介面中的抽象方法 -->
<select id="selectBlog" resultMap="bid">
select *
from tt_blog where id = #{id}
</select>
<insert id="saveBlog" parameterType="Blog">
insert into tt_blog (id,title) values(SEQ_BLOG.nextval,#{title})
</insert>
<update id="updateBlog" parameterType="Blog">
update tt_blog set title = #{title}
<!-- 動態sql,當想更新的內容不為空的時候,則會執行,否則將不會執行 -->
<if test="auth != null">
,auth = #{auth}
</if>
where id = #{id}
</update>
<delete id="deleteBlog">
delete from tt_blog where id = #{id}
</delete>
</mapper>
BlogMapper.java
package com.iflytek.dao;
import com.iflytek.domain.Blog;
public interface BlogMapper {
public Blog selectBlog(Blog blog);
public void saveBlog(Blog blog);
public void updateBlog(Blog blog);
public void deleteBlog(Blog blog);
}
4、代建對應的資料庫和表,本例建立如下
初始化部分資料
5、建立測試類進行測試,這裡對SQLsessionfactory還沒有進行封裝,開發中一般使用單例模式進行封裝,只有一個工廠sessionfactory,可有多個session物件(Test.java)
package com.iflytek.test;
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;
import com.iflytek.dao.BlogMapper;
import com.iflytek.domain.Blog;
public class Test {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(1);
Blog res = mapper.selectBlog(blog);
System.out.println(res.getTitle());
} finally {
session.close();
}
}
}
6、檢視結果(id為1的對應title為1111),正確
’