從 XML 中構(gòu)建 SqlSessionFactory
每個(gè)基于 MyBatis 的應(yīng)用都是以一個(gè) SqlSessionFactory 的實(shí)例為中心的。SqlSessionFactory 的實(shí)例可以通過 SqlSessionFactoryBuilder 獲得休溶。而 SqlSessionFactoryBuilder 則可以從 XML 配置文件或一個(gè)預(yù)先定制的 Configuration 的實(shí)例構(gòu)建出 SqlSessionFactory 的實(shí)例计贰。
從 XML 文件中構(gòu)建 SqlSessionFactory 的實(shí)例蜜猾,建議使用類路徑下的資源文件進(jìn)行配置。但是也可以使用任意的輸入流(InputStream)實(shí)例产还,包括字符串形式的文件路徑或者 file:// 的 URL 形式的文件路徑來配置只估。MyBatis 包含一個(gè)名叫 Resources 的工具類,它包含一些實(shí)用方法掺喻,可使從 classpath 或其他位置加載資源文件更加容易芭届。
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
XML 配置文件(configuration XML)中包含了對(duì) MyBatis 系統(tǒng)的核心設(shè)置储矩,包含獲取數(shù)據(jù)庫連接實(shí)例的數(shù)據(jù)源(DataSource)和決定事務(wù)作用域和控制方式的事務(wù)管理器(TransactionManager)感耙。XML 配置文件的詳細(xì)內(nèi)容后面再探討,示例:
<?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>
<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:///school?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="qwer1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
存放sql語句的xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aa">
<select id="selectStudent" resultType="study.study.bean.User">
select * from student
</select>
</mapper>
用配置的xml從數(shù)據(jù)庫取信息
package study
/**
* Created by Administrator on 2017/10/10.
*/
public class MyTest {
public static void main(String[
![Uploading 10111_195338.jpg . . .]
] args) throws Exception{
InputStream is= Resources.getResourceAsStream("mybatis-config.xml");
//獲取主配置文件
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
//創(chuàng)建工廠對(duì)象
SqlSession sqlSession=factory.openSession();
//獲取sqlsession(相當(dāng)于connection)
List<User> list=sqlSession.selectList("selectStudent");
//當(dāng)返回的是list是用selectlist
//當(dāng)返回的只是一個(gè)對(duì)象的時(shí)候用selectone
//修改操作時(shí)用update
//新增用insert
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
}
補(bǔ)充一下
SqlSession sqlSession=factory.openSession(true);
//獲取sqlsession(相當(dāng)于connection)當(dāng)設(shè)置為true時(shí)持隧,開啟自動(dòng)提交事物
//在對(duì)數(shù)據(jù)庫有改動(dòng)的時(shí)候要提交事物才會(huì)生效
int update=sqlSession.update("com.aa.updateStudent",user);
sqlSession.commit();
//提交
System.out.println(update);
sqlSession.close();
//選擇true的時(shí)候就不需要自己手動(dòng)提交了
10-11
之前是在測試類中用sqlsession執(zhí)行xml文件的sql語句即硼,對(duì)數(shù)據(jù)庫進(jìn)行操作,反正不好屡拨。只酥。。呀狼。
先定義一接口可以看做項(xiàng)目中的dao層
//接口
public interface GoodsMapper {
Goods selectGoodsById();
List<Goods> selectGoodsAll();
int insertGoods(Goods goods);
int updateGoods(Goods goods);
}
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//獲取主配置文件
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//創(chuàng)建工廠對(duì)象
SqlSession sqlSession = factory.openSession(true);
//獲取sqlsession(相當(dāng)于connection)true意思是自動(dòng)提交事物
GoodsMapper mapper = sqlSession.getMapper(GoodsMapper.class);
//通過實(shí)現(xiàn)類拿到接口---這里是接口對(duì)象
Goods goods = new Goods();
goods.setGname("黃瓜");
int a = mapper.insertGoods(goods);
//用接口調(diào)用里面的方法
System.out.println(a);
sqlSession.close();
描述sql語句的xml文件
<mapper namespace="com.study.mapper.GorderMapper">
<!--
1 namespace 與接口全限定名一致
2 id和抽象函數(shù)保持一致
3 參數(shù)類型與返回類型保持一致
4 Java類名與xml文件名保持一致
-->
<select id="selectGorderAll" resultType="Gorder">
select * from gorder
</select>//select標(biāo)簽
<insert id="insertGorder" parameterType="Gorder">
insert into gorder (orderId,createTime,status,price,uid,gid) VALUES (#
{orderId},now(),#{status},#{price},#{uid},#{gid})
</insert>//insert標(biāo)簽
<update id="updateGorder" parameterType="Gorder">//parameterType參數(shù)類型
update Gorder set price = #{price} where orderId = #{orderId}
</update>//update標(biāo)簽
<delete id="removeGorder" parameterType="Gorder">
delete FROM gorder where orderId = #{orderId}
</delete>//delete標(biāo)簽
</mapper>
mybatis-config.xml配置
將原來存于mybatis-config.xml里的jdbc的配置文件放于一個(gè)properties下面
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///taobao?useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.password=qwer1234
在mybatis-config.xml引用properties文件內(nèi)容
<properties resource="jdbc.properties"></properties>
后面的使用properties信息
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClass}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
setting 配置
<settings>
<!-- 日志的實(shí)現(xiàn)類裂允,可以不寫,會(huì)自動(dòng)匹配 -->
<setting name="logImpl" value="LOG4J"/>
<!-- 將數(shù)據(jù)庫字段的下劃線自動(dòng)轉(zhuǎn)為駝峰命名 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 自動(dòng)映射哥艇,F(xiàn)ULL表示無論是否關(guān)聯(lián)都進(jìn)行自動(dòng)映射 -->
<setting name="autoMappingBehavior" value="FULL"/>
</settings>
配置log4j---->日志是在console上輸出的一些內(nèi)部信息绝编,比如執(zhí)行了哪些sql
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.study.mapper=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
別名
resultType參數(shù)返回類型,只寫類名簡寫貌踏,在config.xml配置
<typeAliases>
<package name="com.study.bean"></package>//這里是另bean下面的都可以用別名
</typeAliases>
<!-- 使用的使用直接使用別名Goods十饥,不用寫全限定名 -->com.bean.Goods
<select id="selectGoodsById" resultType="Goods">
select * from goods where gid=3
</select>
輸入映射 parameterType--->
config.xml和存sql 的xml關(guān)聯(lián)起來
<mappers>
<mapper resource="UserMapper.xml"/>
<mapper resource="GoodsMapper.xml"/>
<mapper resource="GorderMapper.xml"/>
</mappers>
后面還有兩個(gè)關(guān)聯(lián)。祖乳。逗堵。log4j沒寫