?
?
接下来用代码来实现
首先编写一个接口mapper
package com.cong.dao;
import com.cong.domain.User;
import java.util.List;
public interface UserMapper {
public List<User> findAll();
}
然后编写映射文件 注意的是: mapper接口要对应 id要对应方法名?
resultType="user"对应输出的实体对应名
parameterType=""输入参数也要对应 对应findAll("parameterType"),这了没有参数所以就没有写
<?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 namespace="com.cong.dao.UserMapper">
<!-- 查询所有-->
<select id="findAll" resultType="user">
select * from tb_user
</select>
</mapper>
然后写一个service层调用dao层
package com.cong.service;
import com.cong.dao.UserMapper;
import com.cong.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserService {
public static void main(String[] args) throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAll();
System.out.println(all);
}
}
编写一个带参数的查询 注意输入参数int 和输出参数user
findById
<!-- 根据id查询实体-->
<select id="findById" parameterType="int" resultType="user">
select * from tb_user where id=#{id}
</select>
编写接口 注意对应参数
public User findById(int id);
测试
?
|