DBUtils 要設置爲單例模式 java
public enum DBUtil { INSTANCE; private SqlSessionFactory sessionFactory; private DBUtil() { String resource = "mybatis-config.xml"; try (Reader reader = Resources.getResourceAsReader(resource)){ sessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } public SqlSessionFactory getSessionFactory() { return sessionFactory; } }
1 有關配置(mybatis-config.xml 文件)mysql
<?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標籤的前面 否則會報錯-->
<settings> <!-- 開啓數據庫下劃線命名方式和 java 駝峯命名方式之間的轉換 --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <!-- 設置別名,使用別名代替原始的名字 --> <typeAlias type="com.rjxy.model.User" alias="_User"/> </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://localhost:3306/數據庫名" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <!-- 使用 xml 的方式配置 --> <!-- 這個是經常使用的方法 --> <mapper resource="UserMapper.xml" /> <!--這個對應另外一個類的Mapper--> <!-- 使用註解的方式配置 --> <mapper class="com.rjxy.dao.CategoryDao"/> </mappers> </configuration>
2 有關UserMapper.xml sql
<?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.rjxy.dao.UserDao">
<insert id="saveUser" parameterType="_User">
insert into user(username, password, email) values (#{username}, #{password}, #{email})
</insert>
<select id="listUser" resultType="_User">
select * from user
</select>
</mapper>
3 註解的方式配置 , 不須要 CategoryMapper.xml (可是不經常使用 , 不方便) 對應上面相同顏色數據庫
4 模糊查詢 , 若是有多個傳參數模糊查詢session
總共有三種方法:mybatis
1. 封裝爲對象
2. 使用 HashMap
3. 使用參數索引:
arg0,arg1,...
param1,param2,...app
select * from user where username like #{value}
listUserByKey("%人%");
<select id="listUserByName" parameterType="String" resultType="_User"> select * from user where username like '%${value}%' </select> dao.listUserByKey("人");
<select id="listUserByNameOrEmail" resultType="_User"> select * from user where username like #{param1} or email like #{param2} </select> <select id="listUserByNameOrEmail" resultType="_User"> select * from user where username like #{arg0} or email like #{arg1} </select>
dao.listUserByNameOrEmail("%a%", "%q%");