1. 程式人生 > >ssm框架學習---mybatis學習檔案結構和程式碼示例

ssm框架學習---mybatis學習檔案結構和程式碼示例

準備工作:mybatis的jar包,資料庫的驅動包,日誌log4j和單元測試的包

開發模式:(1)基於原始dao開發,需要編寫dao介面和dao介面的實現類

                    (2)基於mapper開發,只需編寫dao介面,但是需要遵守一定規範(對映檔案的名稱空間為dao介面全限定名,介面中的方法,引數型別和返回型別和對映檔案中statement語句輸入引數和輸出引數相對應,注意返回結果為集合比較特殊)

框架的結構:(1)SqlMapConfig.xml(Mybatis的全域性配置檔案,配置資料來源、事務、快取等mybatis執行環境),配置對映檔案UserMapper.xml,xxxMapper.xml

                        (2)SqlSessionFactory(會話工廠)用來建立SqlSession

                        (3)SqlSession (會話)操作資料庫(curd)操作

                        (4)Executor(執行器)Sqlsession內部通過執行器來操作資料庫

                        (5)mapped statement(底層封裝物件) 對操作資料庫儲存封裝,包括sql語句,輸入引數、輸出結果型別

工程結構如下:


兩種方式我都寫了,所以這裡會有連個xml對映檔案,並且會有dao和mapper的包,實際開發選擇其中一種(推薦mapper)

首先這裡給出db.properties和log4j.properties這兩個檔案

db.properties

jdbc.driver =com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=admin
log4j.properties
# Global logging configuration
#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
log4j.rootLogger=DEBUG, stdout
# 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
這裡需要注意一下,在我們開發過程,要使用debug模式

sqlmapconfig.xml主要放mybatis的配置檔案如下,主要包括二個部分,第一部分為配置資料來源,第二部分為對映檔案配置

<?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="db.properties">
     <!-- 這中間還可以配置一些其他的屬性,載入時先載入然後再載入外部的配置 -->
     </properties>
     <!-- 配置資料庫環境 -->
     <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="POOLED">
	                <property name="driver" value="${jdbc.driver}"/>
	                <property name="url" value="${jdbc.url}"/>
	                <property name="username" value="${jdbc.username}"/>
	                <property name="password" value="${jdbc.password}"/>
                </dataSource>
            </environment>
     </environments>
     <mappers>
        <mapper resource="sqlmap/User.xml"/>
        <mapper resource="sqlmap/UserMapper.xml"/>
     <!-- 使用批量匯入的方式,需要注意使用mapper代理,並且xml檔案和mapper介面放在同一目錄中-->
     </mappers>
</configuration>
接下來是對映檔案,user.xml和usermapper.xml兩者的區別僅僅在於名稱空間的不同

user.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代理方式很重要 -->
<mapper namespace="test">
   <select id="selectUserById" parameterType="int" resultType="com.zcj.po.User">
      select * from userinfo where id=#{id}
   </select>
</mapper>
usermapper.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代理方式很重要 -->
<mapper namespace="com.zcj.mapper.UserMapper">
   <select id="selectUserById" parameterType="int" resultType="com.zcj.po.User">
      select * from userinfo where id=#{id}
   </select>
</mapper>
接下來就是dao實現方式

UserDao.java

package com.zcj.dao;

import com.zcj.po.User;

public interface UserDao {
     public User selectUserById(int id);
}
UserDaoImpl.java
package com.zcj.dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.zcj.po.User;

public class UserDaoImp implements UserDao {
    private SqlSessionFactory sqlSessionFactory;
    public UserDaoImp(SqlSessionFactory sqlSessionFactory){
    	this.sqlSessionFactory=sqlSessionFactory;
    }
	public User selectUserById(int id) {
		// TODO Auto-generated method stub
		SqlSession sqlSession= sqlSessionFactory.openSession();
		User user = sqlSession.selectOne("test.selectUserById",id);
		return user;
	}
     
}
第二種方式,使用mapper,方法的編寫就要受到一定的限制

UserMapper.java

package com.zcj.mapper;

import com.zcj.po.User;

public interface UserMapper {
    public User selectUserById(int id);
}
到這一步就編寫完了,下面是單元測試,都需要首先得到SqlsessionFactory

mapper方式的測試:

package com.zcj.mapper;

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 org.junit.Before;
import org.junit.Test;

import com.zcj.po.User;

public class UserMapperTest {
        private SqlSessionFactory sqlSessionFactory;
	@Before
	public void setUp() throws Exception {
		String resource ="mybatis/SqlMapConfig.xml";
		InputStream inputStream =Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}

	@Test
	public void testSelectUserById() {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user=userMapper.selectUserById(1);
		System.out.println(user);
	}

}

dao方式的測試類似,只需要把sessionFactory傳給dao的構造方法的引數就可以獲取sqlsession了

package com.zcj.dao;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import com.zcj.po.User;

public class UserDaoImpTest {
	 private SqlSessionFactory sqlSessionFactory;
	@Before
	public void setUp() throws Exception {
		String resource ="mybatis/SqlMapConfig.xml";
		InputStream inputStream =Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}

	@Test
	public void testSelectUserById() {
		UserDaoImp userDaoImp = new UserDaoImp(sqlSessionFactory);
		User user=userDaoImp.selectUserById(1);
		System.out.println(user);
	}

}
最後加上user的pojo

User.java

package com.zcj.po;

public class User {
    private int id;
    private String username;
    private String password;
    private String sex;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", password=" + password + ", sex=" + sex
				+ ", username=" + username + "]";
	}
    
}
學習到這裡,mybatis的單獨使用就大致瞭解了,下面介紹mybatis generator,它是依據資料表自動生成pojo,mapper,和對映檔案

首先需要準備jar包,然後編寫一個配置檔案generator.xml,這裡使用一個方法執行它對應檔案如下:

generator.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
	<context id="testTables" targetRuntime="MyBatis3">
		<commentGenerator>
			<!-- 是否去除自動生成的註釋 true:是 : false:否 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!--資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root"
			password="admin">
		</jdbcConnection>
		<!-- 預設false,把JDBC DECIMAL 和 NUMERIC 型別解析為 Integer,為 true時把JDBC DECIMAL 和 
			NUMERIC 型別解析為java.math.BigDecimal -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- targetProject:生成PO類的位置 -->
		<javaModelGenerator targetPackage="com.zcj.ssm.po"
			targetProject=".\src">
			<!-- enableSubPackages:是否讓schema作為包的字尾 -->
			<property name="enableSubPackages" value="false" />
			<!-- 從資料庫返回的值被清理前後的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
        <!-- targetProject:mapper對映檔案生成的位置 -->
		<sqlMapGenerator targetPackage="com.zcj.ssm.mapper" 
			targetProject=".\src">
			<!-- enableSubPackages:是否讓schema作為包的字尾 -->
			<property name="enableSubPackages" value="false" />
		</sqlMapGenerator>
		<!-- targetPackage:mapper介面生成的位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.zcj.ssm.mapper" 
			targetProject=".\src">
			<!-- enableSubPackages:是否讓schema作為包的字尾 -->
			<property name="enableSubPackages" value="false" />
		</javaClientGenerator>
		<!-- 指定資料庫表 -->
		<table tableName="userinfo" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>  
		<!-- <table schema="" tableName="sys_user"></table>
		<table schema="" tableName="sys_role"></table>
		<table schema="" tableName="sys_permission"></table>
		<table schema="" tableName="sys_user_role"></table>
		<table schema="" tableName="sys_role_permission"></table> -->
		
		<!-- 有些表的欄位需要指定java型別
		 <table schema="" tableName="">
			<columnOverride column="" javaType="" />
		</table> -->
	</context>
</generatorConfiguration>
對應的執行檔案:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GeneratorSqlmap {

	public void generator() throws Exception{

		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		//
		File configFile = new File("generatorConfig.xml"); 
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
				callback, warnings);
		myBatisGenerator.generate(null);

	} 
	public static void main(String[] args) throws Exception {
		try {
			GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
			generatorSqlmap.generator();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}