Mybatis-实现增删改查

通过Mybatis持久化框架实现对数据库表的增删改查的简单例子

(个人心得:我感觉学习一个框架可以先去了解它大致的运行流程,然后再去学习其填充的东西,这样更加容易理解而且在学的过程中也会联系起来。不然一开始就看框架的一些详细解释感觉好难懂)

StyleCategory实体类

package com.mybatis.entity;


/**
 * @author lyx
 *	
 * 2015-9-2下午7:07:57
 *
 *com.mybatis.entity.StyleCategory
 *
 */
public class StyleCategory {

	private int styleId;
	private String styleName;
	
	public int getStyleId() {
		return styleId;
	}
	public void setStyleId(int styleId) {
		this.styleId = styleId;
	}
	public String getStyleName() {
		return styleName;
	}
	public void setStyleName(String styleName) {
		this.styleName = styleName;
	}
	public StyleCategory(int styleId, String styleName) {
		super();
		this.styleId = styleId;
		this.styleName = styleName;
	}
	public StyleCategory(String styleName) {
		super();
		this.styleName = styleName;
	}
	public StyleCategory() {
		super();
	}
	
	
}

styleMapper.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.mybatis.entity.StyleMapper">

	<!-- sql标签 表示可以被其他语句复用的SQL块-->
	<sql id="queryFields">
		styleId,styleName
	</sql>
	
	<!--  -->
	<resultMap type="StyleCategory" id="styleMap">
		
		<!-- 主键映射 -->
		<id property="styleId" column="styleId" javaType="int" />
		<!-- 数据库字段到实体类属性的映射 -->
		<result property="styleName" column="styleName"/>
		
	</resultMap>
	
	
	
	<!-- 根据style查询 -->
	<select id="getStyleById" parameterType="int" resultType="StyleCategory" >
		select
			<include refid="queryFields"></include>
		from STYLE_CATEGORY where styleId=#{styleId}
	</select>
	 
	 <!-- 查询全部 -->
	 <select id="queryAllInfo" resultType="StyleCategory" resultMap="styleMap">
		select 
		*
		 from STYLE_CATEGORY
	</select>
	 
	 
	<!-- 插入  -->
	<!-- 如果使用的是表中自定义的主键就不需要的添加 useGeneratedKeys="true" 否则会报错:列名无效,Error getting generated key or setting result to parameter object-->
	<!-- 设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。MySQL和SQLServer执行auto-generated key field,
		因此当数据库设置好自增长主键后,可通过JDBC的getGeneratedKeys方法获取。但像Oralce等不支持auto-generated key field的数据库就不能用这种方法获取主键了 -->
	 <insert id="addStyleInfo" parameterType="StyleCategory"  keyProperty="styleId">
		<!-- <selectKey resultType="StyleCategory" order="BEFORE" keyProperty="styleId">
			 select SEQUENCE_STYLECATEGORY.nextval as STYLEID from dual; 
		</selectKey> -->
		
		insert into STYLE_CATEGORY (styleId,styleName) values (SEQUENCE_STYLECATEGORY.nextval,#{styleName})
	</insert>
	
	<!-- 更新 -->
	<update id="updateStyleInfo" parameterType="StyleCategory" >
		update STYLE_CATEGORY set styleName=#{styleName} where styleId=#{styleId}
	
	</update>
	 
	<!-- 删除 -->
	<delete id="deleteStyleInfoById" parameterType="int">
		delete  from STYLE_CATEGORY where styleId =#{styleId}
	</delete>

	
    
</mapper>

mybatis主配置文件

<?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标签 是写实体类的别名,写了之后可以在写类的映射文件例如<select>标签中的属性就可以不用写实体的具体路径直接用别名 -->
	 <typeAliases>
		<typeAlias type="com.mybatis.entity.StyleCategory" alias="StyleCategory"/>
	</typeAliases> 
	
	
	<!-- 数据库配置 -->
	
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC"></transactionManager>
				<dataSource type="POOLED">
					<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
					<property name="driver"  value="oracle.jdbc.driver.OracleDriver"></property>
					<property name="username" value="lyx"></property>
					<property name="password" value="lyx"></property> 				
				</dataSource>		
		</environment>
	</environments>
	
	<!-- 映射文件 -->
	<mappers>
		<mapper resource="mapper/styleMapper.xml"/>
	</mappers>
	
	
  
</configuration>

测试类

package test;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

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 com.mybatis.entity.StyleCategory;

public class MainTest {

	public  static void main(String[] args) throws IOException
	{
		//读取配置文件
		Reader reader =Resources.getResourceAsReader("mybatis-config.xml");
		
		SqlSessionFactory sqlSession =new SqlSessionFactoryBuilder().build(reader);
		
		//打开session会话
		SqlSession	session = sqlSession.openSession();
		
		
		//查询
		StyleCategory style = session.selectOne("com.mybatis.entity.StyleMapper.getStyleById",2);
		System.out.println("style:"+style.getStyleId()+","+style.getStyleName());
		
	
		//删除
		int deleteNum=session.delete("com.mybatis.entity.StyleMapper.deleteStyleInfoById",22);
		
		if(deleteNum>0)
		{
			System.out.println( deleteNum +"删除成功!");
		}
	
		
		//更新
		StyleCategory updateStyle = new StyleCategory(2,"刘育新");
		
		int updateNum=session.update("com.mybatis.entity.StyleMapper.updateStyleInfo",updateStyle);
		
		if(updateNum>0)
		{
			System.out.println( updateNum +"更新成功!");
		}
		
		
		//插入数据
		StyleCategory insertStyle = new StyleCategory("大中华");
		int insertNum =session.insert("com.mybatis.entity.StyleMapper.addStyleInfo",insertStyle);
		if(insertNum>0)
		{
			System.out.println(insertNum+"插入成功");
		}
		
		
		//查询全部
		List<StyleCategory> list=session.selectList("com.mybatis.entity.StyleMapper.queryAllInfo");
		for (StyleCategory styleCategory : list) {
			System.out.println(styleCategory.getStyleId()+":"+styleCategory.getStyleName());
		}
		
		//提交session会话,否则操作数据库无效
		session.commit();
		
	}
}

源代码下载:http://download.csdn.net/detail/u013147600/9074495

你可能感兴趣的:(mybatis,SqlSession)