当前位置 : 主页 > 编程语言 > java >

Mybatis注解增删改查的实例代码

来源:互联网 收集:自由互联 发布时间:2021-04-03
要点 有另一种方法来完成语句映射。 它们映射的语句可以不用 XML 来配置,而可以使用 Java 注解来配置。 使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句

要点

有另一种方法来完成语句映射。 它们映射的语句可以不用 XML 来配置,而可以使用 Java 注解来配置。

使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。

如果你需要做一些很复杂的操作,最好用 XML 来映射语句。

需要在config.xml中注册Java接口

<mappers>
 <mapper class="com.mybatis.DAO.PeopleMapper"/>
</mappers>

要用class=


public interface PeopleMapper {
 @Select("select * from people")
 List<People> getPeopleList();
}


可以先开启事务自动提交

public static SqlSession getSqlSession(){
  return sqlSessionFactory.openSession(true);
 }
}

Mapper.java

public interface PeopleMapper {
 @Select("select * from people")
 List<People> getPeopleList();
 @Insert("insert into people(id, name, age, address) VALUES (#{id},#{name},#{age},#{address})")
 int addPeople(People people);
}

test

public class PeopleDAOtest {
 @Test
 public void print() {
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
  List<People> people = peopleMapper.getPeopleList();
  for (People p :people){
   System.out.println(p);
  }
  sqlSession.close();
 }
 @Test
 public void add(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
  peopleMapper.addPeople(new People(6,"圣迭戈",456,"啥地方"));
  print();
 }
}

因为已经自动提交了,所以不需要sqlSession.commit();

注解@Param

只能用于基本数据类型

传入的参数只能和sql语句中参数一样

多个参数

样例

public interface PeopleMapper {
 @Delete("delete people from people where id=#{uid}")
 int delPeople(@Param("uid") int i);
}

test

public class PeopleDAOtest {
 @Test
 public void del(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
  peopleMapper.delPeople(6);
  print();
 }
}


Mapper.java

public interface PeopleMapper {
 @Update("update mybatis.people set name=#{name} ,age=#{age} ,address=#{address} where id=#{id}")
 int updateP(People people);
}

test

public class PeopleDAOtest {
 @Test
 public void update(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
  peopleMapper.updateP(new People(5,"圣迭戈",456,"啥地方"));
  print();
 }
}

总结

到此这篇关于Mybatis注解增删改查的文章就介绍到这了,更多相关Mybatis注解增删改查内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

网友评论