MyBatis快速入门——第二章、DML语句操作_sql

MyBatis快速入门——第二章、DML语句操作

目录

​在接口类中添加【UsersMapper.java】​

​修改【com.item.mapper.UsersMapper.】​

​【action.java】​


在接口类中添加【UsersMapper.java】

/**
* 添加
* @param nickName
* @param sex
* @param age
* @param introduce
* @return
*/
int AddInfo(@Param("nickName")String nickName,
@Param("sex")int sex,
@Param("age")int age,
@Param("introduce")String introduce);

/**
* 修改
* @param nickName
* @param id
* @return
*/
int UpdateInfo(@Param("nickName")String nickName,
@Param("id")int id);

/**
* 删除
* @param id
* @return
*/
int DeleteById(@Param("id")int id);

修改【com.item.mapper.UsersMapper.】

<insert id="AddInfo">
insert into users values(0,Now(),"${nickName}",${sex},${age},"${introduce}");
</insert>
<update id="UpdateInfo">
update users set nickName="${nickName}" where id=#{id}
</update>
<delete id="DeleteById">
delete from users where id=#{id}
</delete>

【action.java】

public static void main(String[] args) throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sessionFactory.openSession();
UsersMapper db = sqlSession.getMapper(UsersMapper.class);
//添加
int rows = db.AddInfo("安琦", 0, 20, "美貌");
System.out.println(rows>0?"添加成功":"添加失败");
rows = db.UpdateInfo("安琦", 5);
System.out.println(rows>0?"修改成功":"修改失败");
rows = db.DeleteById(6);
System.out.println(rows>0?"删除成功":"删除失败");
sqlSession.commit();
sqlSession.close();
}

执行效果: 

MyBatis快速入门——第二章、DML语句操作_sql_02