您的位置:首页 > 其它

MyBatis基础操作

2017-04-23 15:19 330 查看

增改删操作:

map配置文件中,有Insert,Update,delete等标签用来对应增改删操作。

MyBatis中很重要的一点是:它可以自动检测传入参数对象的属性和sql语句中参数的属性是否在name和类型上匹配的话,就会进行自动替换。同样对于resultType也是一样

Insert标签,插入

<insert id="insertUser" parameterType="User" statementType="PREPARED"
keyProperty="id" useGeneratedKeys="true">
insert into User (userName,password) values
(#{userName,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR})
</insert>

//id:                       用于标识该insert sql语句
//parameterType:            标识传入的参数类型
//keyProperty:              用于定义主键,useGeneratedKeys使用自增,这里插入中缺省了ID这个主键,所以在这里定义一下主键

//jdbcType                  对应JDBC中的类型
//typeAliases               标记定义别名,这里的User就已经是别名,本来需要完全限定名

//#{username}就是代表参数

测试代码:

User one=new User();
one.setName("author001");
one.setPassword("123456");
session.insert("insertUser",one);


Update标签,更新

<update id="updateUser" parameterType="User">
UPDATE User SET  userName = #{userName,jdbcType=VARCHAR},
password =#{password,jdbcType=VARCHAR}
WHERE id = #{id,jdbcType=INTEGER}
</update>


简单查询:

Select

Select的所有配置

<select   id=”selectPerson” parameterType=”int”
parameterMap=” hashmap” resultType=”hashmap” resultMap=”personResultMap”
flushCache=”false” useCache=”true” timeout=”10000” fetchSize=”256”
statementType=”PREPARED” resultSetType=”FORWARD_ONLY” >


parameterType封装:对象

1. 对象参数自动匹配属性

2. 如果对象属性与列名不一样用别名

//parameterType封装:hashmap
//MyBatis同样会自动匹配hashmap中和参数 nama和类型一样的进行替换

<select id="loginSelect" resultType="User" parameterType="hashmap">
select * from User where userName=#{userName} and password=#{password}
</select>

//测试
HashMap<String,String> hm=new HashMap();
hm.put("userName", "e0001");
hm.put("password","123456");
JiKeUser onetemp=session.selectOne("loginSelect",hm);

//返回多行记录时MyBatis自动封装成List
<select id="selectJiKeUserList" resultType="User">
select * from User
</select>

//测试代码:
List<User> ap=session.selectList("selectUserList");
for(User temp:ap) {
System.out.println("用户名="+temp.getUserName());
}


resultType与 resultMap

两者只能有一个成立

resultMap解决复杂查询时的映射问题

<resultMap id="UserMap" type="User">
<id property="id" column="id" />
<result property="userName" column="userName"/>
<result property="password" column="password"/>
</resultMap>

//使用resultMap前,要先定义:
<select id="selectUsers" resultMap="UserMap">
select id, userName, password from User
</select>


resultMap简单的讲,它的作用就是结果映射。上面这个例子,我们可以直接使用resultType = “User”,因为User的属性和数据库字段名称完全匹配。resultMap一般用于返回结果的属性和数据库字段不匹配时,进行映射的。比如返回类型有个属性为userName,而数据库中对应的字段为user_name,这时候无法进行自动匹配,只能通过resultMap手动映射。

当然我们只要匹配返回类型中和数据库中不匹配的属性,省略的那些匹配的属性还是会自动替换过来的!!

事物:

mybatis事务由两种方式控制:

JDBC:由JDBC来处理

MANAGED:由第三方插件来处理,比如Spring

<environment id="development">
<transactionManager type="JDBC" />
……
</environment>


Mybatis JDBC事务管理(典型代码)

try{
session=sqlMapper.openSession(false); //关闭自动提交
……
session.commit(); //提交事务
}
catch(Exception e)
{   session.rollback();} //回滚事务
finally
{   session.close();} //关闭session
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis