赞
踩
(从有道云笔记搬运,博客做备份)
public interface PlayersDao { //查询选手信息列表 List<Players> getPlayersList(); //查询选手信息,通过id Players getPlayersById(String id); //插入选手信息 int insertPlayersInfo(Players player); //更新选手信息,通过id int updatePlayersInfoById(Players player); //删除选手信息,通过id int deletePlayersInfoById(String id); }
<?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对应的就是dao,namespace就是对应dao层的地址,绑定接口 --> <mapper namespace="com.study.mybatis.dao.PlayersDao"> <!-- id是对应方法的名字,resultType是返回类型 --> <select id="getPlayerList" resultType="com.study.mybatis.pojo.Players"> <!-- 这里面写的是sql --> select * from players; </select> <select id="getPlayersById" resultType="com.study.mybatis.pojo.Players" parameterType="java.lang.String"> select * from players where id = #{id}; </select> <insert id="insertPlayersInfo" parameterType="com.study.mybatis.pojo.Players"> insert into players(id,team,situation) values(#{id}, #{team}, #{situation}); </insert> <update id="updatePlayersInfoById" parameterType="com.study.mybatis.pojo.Players"> update players set team = #{team}, situation = #{situation} where id=#{id}; </update> <delete id="deletePlayersInfoById" parameterType="java.lang.String"> delete from players where id = #{id}; </delete> </mapper>
@Test public void test() { //获取sqlSession SqlSession sqlSession = MybatisUtils.getSqlSession(); //获取mapper(Dao) PlayersDao playersDao = sqlSession.getMapper(PlayersDao.class); //执行SQL /* * List<Players> players = playersDao.getPlayersList(); for (Players p : * players) { System.out.println(p.getTeam() + "-" + p.getSituation() + "-" * +p.getId()); } */ //增删改查 //这里写mapper,方便理解(现在已经理解了,就不用dao来命名了) PlayersDao mapper = playersDao; //查 Players p = mapper.getPlayersById("BurNing"); System.out.println(p.getTeam() + "-" + p.getSituation()); //add int res = mapper.insertPlayersInfo(new Players("yueru", "DK", "二号位")); //成功,res = 1 if (res > 0) { System.out.println("插入成功,提交事务"); sqlSession.commit(); }else { System.out.println("插入失败,回滚事务"); sqlSession.rollback(); } //改 res = mapper.updatePlayersInfoById(new Players("yueru", "DK", "二号位")); //成功,res = 1 if (res > 0) { System.out.println("插入成功,提交事务"); sqlSession.commit(); }else { System.out.println("插入失败,回滚事务"); sqlSession.rollback(); } //删 res = mapper.deletePlayersInfoById("2009"); if (res > 0) { System.out.println("删除成功,提交事务"); sqlSession.commit(); }else { System.out.println("删除失败,回滚事务"); sqlSession.rollback(); } //关闭sqlSession sqlSession.close(); }
insert和update没有返回类型
增删改需要提交事务(commit)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。