Mybaits总结--Mybaits的简单使用

一、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());
	}
}

猜你喜欢

转载自blog.csdn.net/qq_25011427/article/details/83758955