在mybatis中针对CRUD一共有四个注解:
@Select(),@Delete(),@Insert(),@Update()
示例:
在mybatis-config.xml中
<mappers>
<!-- <package name="net.togogo.dao"></package>-->
<mapper class="net.togogo.dao.IUserDao"></mapper>
</mappers>
/**
* 查询所有操作
* @return
*/
@Select("select * from user")
List<User> findAll();
/**
* 根据Id查询
*/
@Select("select * from user where id = #{id}")
User findById(Integer id);
当User类中的属性名和数据库的字段名不一致时可以这样:
一对一
mybatis-config.xml中:
<mapper class="net.togogo.dao.IAccountDao"></mapper>
IAccountDao.java中
package net.togogo.dao;
import net.togogo.bean.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
public interface IAccountDao {
/**
* 查询所有操作
* @return
*/
@Select("select * from account")
@Results(id = "accountmap",value = {
@Result(id=true,column ="id",property = "id"),
@Result(column ="uid",property = "uid"),
@Result(column ="money",property = "money"),
@Result(column = "uid",property = "user",
one = @One(select = "net.togogo.dao.IUserDao.findById",
fetchType = FetchType.EAGER))
})
List<Account> findAll();
}
测试类:
@Test
public void findAllAccount() throws IOException {
//4.使用SqlSession创建Dao接口的代理对象
IAccountDao iAccountDao = session.getMapper(IAccountDao.class);
//5.使用代理对象执行方法
List<Account> accounts = iAccountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
System.out.println(account.getUser());
}
运行结果:
来源:CSDN
作者:my vow
链接:https://blog.csdn.net/weixin_41605945/article/details/104347570