Mybaits總結--Mybaits的簡單使用
阿新 • • 發佈:2018-11-12
一、Mybaits的簡單使用
1、匯入jar包
commons-logging-1.1.1.jar,mybatis-3.1.1.jar
2、Mybaits的配置檔案(名字可以隨意,這邊去conf.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="db.properties"></properties> <!-- 配置類的別名 --> <typeAliases> <!-- <typeAlias type="zhuojing.mybaits.helloword.bean.User" alias="_user"/> --> <package name="zhuojing.mybaits.helloword.bean"/> </typeAliases> <!-- development : 開發模式 work : 工作模式 --> <plugins> <plugin interceptor="zhuojing.mybaits.intercept.pageInterceptor"></plugin> </plugins> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${userName}" /> <property name="password" value="${passWord}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="zhuojing/mybaits/helloword/bean/userMapper.xml"/> </mappers> </configuration>
注:這邊設定了類的別名使用 typeAliases 節點來配置
a:typeAlias 子節點:type 屬性為類的全類名,alias 屬性別名的值,使用時只需呼叫別名即可,不用寫全類名(對映檔案中應用)
b:package:name 屬性指定某個包的路徑,使用時配置的包只需寫類名,不需要寫全類名(對映檔案中應用)
3、對映檔案(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 namespace="zhuojing.mybaits.helloword.bean.userMapper"> <!-- 根據id查詢得到一個user物件 --> <select id="getUser" parameterType="int" resultType="User"> select * from user where id=#{id} </select> <select id="getUser1" parameterType="int" > select * from user where id=#{id} </select> </mapper>
4、實體User
public class User {
//省去getter和setter
private Integer id;
private String name;
private Integer age;
}
5.Mybaits的使用
public class HelloWorldTest { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //System.out.print(HelloWorldTest.class.getClassLoader().getResource("conf.xml")); String path = "conf.xml"; InputStream in = HelloWorldTest.class.getClassLoader().getResourceAsStream(path); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in); SqlSession session = sessionFactory.openSession(); String statement = "zhuojing.mybaits.helloword.bean.userMapper.getUser"; User user = session.selectOne(statement, 1); System.out.println(user); } }
二、結合Spring使用
Mybaits結合Spring使用,本質是把資料來源,sqlSessionFactory等Mybaits用到的類交給了Spring 的IOC去管理
1、Mybaits的配置檔案(可以有可以沒有)
<?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>
<!-- 使用列別名替換列名 預設:true -->
<setting name="useColumnLabel" value="true"/>
<!-- 開啟駝峰命名轉換:Table(creat_time : creatTime) -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</configuration>
這邊配置檔案用於設定一個全域性屬性,比如資料庫方言等
2、加入Spring jar包和mybatis-spring-1.2.1.jar
3、實體
public class SMUser {
private int id;
private String name;
private Date birthday;
private double salary;
}
4、Dao介面類SmUserMapper
public interface SmUserMapper {
void save(SMUser smUser);
void update(SMUser user);
void delete(int id);
SMUser findById(int id);
List<SMUser> findAll();
void deleteBatch(List<Integer> ids);
void insertBatch(List<SMUser> smUsers);
}
5、mapper對映檔案(名字和Dao介面名字相同)smuserMapper.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">
<!--
namespace: 必須是介面的全類名
掃描mapper包下的所有mapper檔案和類,要求mapper配置檔案和類名需要一致。
-->
<mapper namespace="zhuojing.mybaits.sm.dao.SmUserMapper">
<!--
id: 必須為介面對應的方法
-->
<insert id="save" parameterType="SMUser">
insert into s_user(user_name,user_birthday, user_salary) values(#{name}, #{birthday},#{salary})
</insert>
<delete id="delete" parameterType="int">
delete from s_user where user_id = #{id}
</delete>
<update id="update" parameterType="SMUser">
update s_user set user_name = #{name}, user_birthday=#{birthday}, user_salary=#{salary} where user_id = #{id}
</update>
<select id="findById" resultType="SMUser" parameterType="int">
select user_id id, user_name name, user_birthday birthday, user_salary salary from s_user where user_id = #{id}
</select>
<select id="findAll" resultType="SMUser">
select user_id id, user_name name, user_birthday birthday, user_salary salary from s_user
</select>
<!-- 批量刪除 -->
<!-- foreach 標籤的 separator 屬性做作用為內容的分隔符-->
<delete id="deleteBatch" parameterType="java.util.List">
delete from s_user where user_id in(
<foreach collection="list" item="item" separator=",">
#{item}
</foreach>
)
</delete>
<insert id="insertBatch" parameterType="java.util.List">
insert into s_user(user_name,user_birthday, user_salary) values
<foreach collection="list" item="item" separator=",">
(#{item.name}, #{item.birthday},#{item.salary})
</foreach>
</insert>
</mapper>
6、Spring配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- 配置資料來源 -->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybaits"></property>
<property name="username" value="root"></property>
<property name="password" value="密碼"></property>
</bean>
<!-- 配置SQLSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="typeAliasesPackage" value="zhuojing.mybaits.sm.domain;zhuojing.mybaits.page.bean"/>
<property name="configLocation" value="classpath:config.xml"></property>
</bean>
<!--
3. mybatis自動掃描載入Sql對映檔案 : MapperScannerConfigurer
sqlSessionFactory / basePackage
-->
<bean id="config" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="zhuojing.mybaits.sm.dao;zhuojing.mybaits.page.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 4. 事務管理 : DataSourceTransactionManager -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"></property>
</bean>
<!-- 5. 使用宣告式事務 -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
7、測試類(這邊使用@RunWith(SpringJUnit4ClassRunner.class)和@ContextConfiguration("/applicationContext.xml")註解來載入Spring環境,也可以使用配置web.xml然後啟動專案進行測試)
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import zhuojing.mybaits.sm.dao.SmUserMapper;
import zhuojing.mybaits.sm.domain.SMUser;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext.xml")
public class SMTest {
@Autowired
private SmUserMapper userMapperDao;
@Test
public void query(){
//SMUser user = new SMUser(-1, "Tom", new Date(), 1000.20);
//userMapperDao.save(user);
System.out.println(userMapperDao.findAll());
}
@Test
public void add(){
SMUser user = new SMUser(-1, "Tom", new Date(), 1000.20);
userMapperDao.save(user);
//System.out.println(userMapperDao.findAll());
}
}