Mybatis註解增刪改查的實例代碼

要點

有另一種方法來完成語句映射。 它們映射的語句可以不用 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註解增刪改查內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: