一、在resource文件夾下建立Configure.xmlphp
<?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 alias="Test" type="com.jd.mybatis.bean.Test" /> </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://127.0.0.1:3306/dss" /> <property name="username" value="root" /> <property name="password" value="123" /> </dataSource> </environment> </environments> <mappers> <!-- // power by http://www.yiibai.com --> <mapper resource="config/Test.xml" /> </mappers> </configuration>
二、建立Test的數據表映射文件Test.xmljava
<?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="TestMapper"> <select id="selectUserByID" parameterType="int" resultType="com.text.Test"> select * from `test` where id = #{id} </select> <select id="findAll" resultType="com.text.Test"> select * from `test` </select> </mapper>
項目結構mysql
如果沒有resource文件夾 可直接新建,而後經過如下步驟變爲資源文件夾sql
建立MyBatisUtil工具類apache
package config; 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 java.io.IOException; import java.io.InputStream; public class MyBatisUtil { public static SqlSessionFactory sqlSessionFactory; public static ThreadLocal<SqlSession> tl=new ThreadLocal<SqlSession>(); static{ InputStream stream=null; try { //讀取mybatis-config配置文件 stream = Resources.getResourceAsStream("config/Configure.xml"); //建立SqlSessionFactory對象 sqlSessionFactory= new SqlSessionFactoryBuilder().build(stream); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("讀取配置文件失敗"); }finally{ try { stream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //獲取SqlSession對象 public static SqlSession openSqlSession(){ SqlSession sqlSession = tl.get(); if(sqlSession==null){ sqlSession=sqlSessionFactory.openSession(); tl.set(sqlSession); } return sqlSession; } public static SqlSession openSqlSession(boolean isAutoCommit){ SqlSession sqlSession = tl.get(); if(sqlSession==null){ sqlSession=sqlSessionFactory.openSession(isAutoCommit); tl.set(sqlSession); } return sqlSession; } }
項目結構session
直接 測試mybatis
public List<Test> getTest(){ SqlSession sqlSession = MyBatisUtil.openSqlSession(false); List<Test> user = sqlSession.selectList("TestMapper.findAll"); sqlSession.commit(); sqlSession.close(); return user; }
至此mybatis建立成功。app