使用mybatis查询
- 配置文件
在mybatis配置文件中,需要配置数据源、mapper文件路径、类型别名等信息。
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
<typeAliases>
<typeAlias type="com.example.mybatisdemo.User" alias="User"/>
</typeAliases>
</configuration>
- Mapper文件
在Mapper文件中定义SQL语句和参数映射。
<mapper namespace="com.example.mybatisdemo.UserMapper">
<select id="getUserById" resultType="User">
select * from user where id = #{id}
</select>
</mapper>
- Java代码
使用SqlSession进行查询操作。
public class UserDao {
private static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public User getUserById(int id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("com.example.mybatisdemo.UserMapper.getUserById", id);
sqlSession.close();
return user;
}
}
以上是使用mybatis进行查询的基本步骤,具体操作可以根据业务需求进行调整。
原文地址: http://www.cveoy.top/t/topic/bk2o 著作权归作者所有。请勿转载和采集!