MyBatis(2):MyBatis标签以及对应的属性用法讲解

通过上一章的讲解,大家应该对MyByatis的基本用法有了一定的了解。这一章主要是讲一下MyBatis的各种标签以及对应的属性,它们的用法以及用的时候应该注意一些什么!下面的讲解时结合当前主流框架(Spring+Spring MVC+MyBatis)以及Oracle数据库进行介绍。其他情况可以参照,不同框架不同数据库可能会存在某些差异。本章将向user_table表中加一个学生主键studentId,student_table表如下

create table student_table(  
  studentId          int     not null,  
  studentName        varchar(20) not null,  
  constraint userId primary key ( userId  )  
);  

讲解上面内容之前需要先了解一下jdbcType和javaType:
JDBC Type类型            Java Type类型  
CHAR                 String  
VARCHAR              String  
LONGVARCHAR          String  
NUMERIC              java.math.BigDecimal  
DECIMAL              java.math.BigDecimal  
BIT                  boolean  
BOOLEAN              boolean  
TINYINT              byte  
SMALLINT             short  
INTEGER              int  
BIGINT               long  
REAL                 float  
FLOAT                double  
DOUBLE               double  
BINARY               byte[]  
VARBINARY            byte[]  
LONGVARBINARY        byte[]  
DATE                 java.sql.Date  
TIME                 java.sql.Time  
TIMESTAMP            java.sql.Timestamp  
CLOB                 Clob  
BLOB                 Blob  
ARRAY                Array  
DISTINCT             mapping of underlying type  
STRUCT               Struct  
REF                  Ref  
DATALINK            java.net.URL[color=red][/color]  
对应接口的xml文件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="com.mybatis.mapper.UserMapper" >  
	<resultMap id="UserVO" type="com.mybatis.VO.UserVO">  
        <id property="userId" column="userId" javaType="java.lang.Integer"></id>  
        <result property="userName" column="userName" javaType="java.lang.String"></result>  
        <result property="userAge" column="userAge" javaType="java.lang.String"></result>  
        <result property="userPhone" column="userPhone" javaType="java.lang.String"></result>  
	<association column="studentId" property="studentId" resultMap="com.mybatis.mapper.StudentMapper.StudentVO"/>
    </resultMap>  
</mapper>

<?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.mapper.StudentMapper" >  
	<resultMap id="StudentVO" type="com.mybatis.VO.StudentVO">  
        <id property="studentId" column="studentId" javaType="java.lang.Integer"></id>  
        <result property="studentName" column="studentName" javaType="java.lang.String"></result>   
    </resultMap>  
</mapper>


UserMapper.xml 是对UserMapper.java 接口的实现。他们之间的关联通过UserMapper.xml 中的<mapper ></mapper> 标签中的namespace属性实现绑定,namespace的属性值为mapper所在的包路径
association :先知道怎么用就行,后面会详细介绍用法
一、insert,delete,update,select标签以及对应的属性

1.insert标签
insert标签分为两种情况:
一种是数据库(如MySQL,SQLServer)支持自动生成主键,另一种是数据库(如Oracle)不支持自动生成主键。下面是不自动生成主键,如果为自动生成主键userId不用插入。

<insert id="save" parameterType="com.mybatis.VO.UserVO">
	INSERT INTO user_table(
	userId, userName,
	userAge,userPhone,studentId)
	values (
	#{userId,jdbcType=INTEGER},#{userName,jdbcType=CHAR},
	#{userAge,jdbcType=INTEGER},#{userPhone,jdbcType=VARCHAR}
	,#{studentId.pk,jdbcType=CHAR})
</insert>

id:id是命名空间中的唯一标示符,可被用来代表这条语句。一个命名空间(namespace)对应一个接口,这个id也应该对应接口里的某个方法(必    须一致),不一致会报错!parameterType:参数类型;
statementType:取值范围STATEMENT,PREPARED(默认值),CALLABLE;
flushCache:取值范围true(默认值)|false,设置执行该操作后是否会清空二级缓存和本地缓存;
timeout:默认为unset(依赖jdbc驱动器的设置),设置执行该操作的最大时限,超时将抛异常;

批量插入方式

<insert id="save" parameterType="java.util.List">
	INSERT INTO user_table(
	userId, userName,
	userAge,userPhone)
	<foreach collection="list" item="item" index="index" open="(" close=")" separator="union all">
		SELECT #{item.userId}, #{item.userName},
			   #{item.userAge}, #{item.userPhone} FROM DUAL
	</foreach>
</insert>

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有 item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
 
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成
2.delete标签

<delete id="delete" parameterType="String">
	delete from user_table where userId=#{userId,jdbcType=CHAR}
</delete>


批量删除

<delete id="delete" parameterType="java.util.List">
	delete from user_table where userId in
	<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
        #{item,jdbcType=CHAR}
    </foreach>
</delete>

3.update标签
具体属性与insert标签一致

<update id="updateUser" parameterType="com.mybatis.VO.UserVO">  
    update user_table set userName=#{userName},userAge=#{userAge},userPhone=#{userPhone} where userId=#{id}  
</update> 

4.select标签
select标签属性
id:在命名空间中唯一的标识符,可以被用来引用这条语句。
parameterType:将会传入这条语句的参数类的完全限定名或别名。
resultType:从这条语句中返回的期望类型的类的完全限定名或别名。注意如果是集合情形,那应该是集合可以包含的类型,而不能是集合本身。使用 resultType 或resultMap,但不能同时使用。
resultMap:外部 resultMap 的命名引用。结果集的映射是 MyBatis 最强大的特性,对其有一个很好的理解的话,许多复杂映射的情形都能迎刃而解。使用 resultMap 或resultType,但不能同时使用。
flushCache:将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:false。
useCache:将其设置为 true,将会导致本条语句的结果被二级缓存,默认值:对 select 元素为 true。
timeout:这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)。
fetchSize:这是尝试影响驱动程序每次批量返回的结果行数和这个设置值相等。默认值为 unset(依赖驱动)。
statementType:STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。
resultSets:这个设置仅对多结果集的情况适用,它将列出语句执行后返回的结果集并每个结果集给一个名称,名称是逗号分隔的。

 <select id="selectUserById" parameterType="int" resultMap="UserVO">  
        select <include refid="column" /> 
	from user_table 
	<include refid="where"/>
 </select> 

<include refid="column" />:引用sql片段可以减少代码冗余

<sql id="columns">
       userId, userName, userAge,userPhone
</sql>

<include refid="where"/>:引用sql片段可以减少代码冗余

<sql id="where">
	<where>
		<if test="userId !=null and userId !=''">
			AND A.userId = #{userId,jdbcType=CHAR}
		</if>
	</where>
</sql>

耐心之树,结黄金之果。

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis 是一种持久层框架,它可以简化 Java 开发人员与数据库之间的交互。MyBatis 提供了一种将 SQL 语句与 Java 代码分离的方法,使得代码更加易于维护和升级。下面,我将详细介绍 MyBatis 如何实现数据库的增删改查操作。 首先,需要在项目中引入 MyBatis 的依赖。可以在 Maven 中添加以下依赖: ```xml <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> ``` 接下来,需要配置 MyBatis 的配置文件,这个配置文件包括了数据源、事务管理器、mapper 映射文件等信息。MyBatis 的配置文件通常命名为 `mybatis-config.xml`,示例配置如下: ```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> <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/test" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/example/mapper/UserMapper.xml" /> </mappers> </configuration> ``` 上述配置中,定义了数据源的信息,包括数据库驱动、URL、用户名和密码。同时,还定义了一个 `UserMapper.xml` 文件,该文件用于映射 SQL 语句。 然后,就可以创建一个 mapper 接口,使用注解或 XML 文件映射 SQL 语句,示例代码如下: ```java public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User getUserById(int id); @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})") @Options(useGeneratedKeys = true, keyProperty = "id") int addUser(User user); @Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}") int updateUser(User user); @Delete("DELETE FROM user WHERE id = #{id}") int deleteUser(int id); } ``` 上述代码定义了一个 `UserMapper` 接口,其中使用了 `@Select`、`@Insert`、`@Update` 和 `@Delete` 四个注解,分别对应查询、插入、更新和删除操作。注解中的 SQL 语句可以直接写在注解中,也可以使用 XML 文件来映射 SQL 语句。 最后,在代码中使用 `SqlSessionFactory` 和 `SqlSession` 对象来执行 SQL 语句,示例代码如下: ```java SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); SqlSession session = sessionFactory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class); User user = new User(); user.setName("张三"); user.setAge(25); userMapper.addUser(user); session.commit(); User user2 = userMapper.getUserById(user.getId()); System.out.println(user2); user.setName("李四"); user.setAge(30); userMapper.updateUser(user); session.commit(); userMapper.deleteUser(user.getId()); session.commit(); session.close(); ``` 上述代码中,首先创建了一个 `SqlSessionFactory` 对象,然后调用 `openSession()` 方法创建一个 `SqlSession` 对象。接着,通过 `session.getMapper(UserMapper.class)` 方法获取到一个 `UserMapper` 对象,然后就可以使用 `UserMapper` 接口中定义的方法执行 SQL 语句。 最后,需要调用 `session.commit()` 方法提交事务,并通过 `session.close()` 方法关闭 `SqlSession` 对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值