mybatis基于XML的映射语音来实现。
尝试写demo。
1 方案一:基于XML
1.1 所需架包。
mybatis-3.3.0.jar
mysql-connector-java-5.1.39-bin.jar
1.2 mybatis配置文件。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<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://127.0.0.1:3307/test" />
<property name="username" value="root" />
<property name="password" value="123123" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/tang/text/pojo/sql/UserMapper.xml"/>
</mappers>
</configuration>
1.3 SQL文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="com.tang.text.dao.UserMapper" >
<!-- 显示所有用户 -->
<select id="getAllUser" resultType="com.tang.text.pojo.User">
SELECT * FROM user
</select>
</mapper>
1.4 SQL映射的接口:
public interface UserMapper {
/**
* 显示所有用户
* @return
*/
List<User> getAllUser();
}
1.5 实体类:
public class User implements Serializable {
private Integer id;
private String name;
private String password;
//省略set和get方法
1.6 测试:
public static void main(String[] args) throws IOException {
Text.query();
}
public static void query() throws IOException {
// 配置文件的位置
String resStr = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resStr);
// 构建SqlSession工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// 获取SqlSession实例
SqlSession session = sqlSessionFactory.openSession();
try {
// 获取对应的mapper接口
UserMapper userMapper = session.getMapper(UserMapper.class);
// 执行SQl操作
List<User> lstUser = userMapper.getAllUser();
System.out.println(lstUser.get(0));
} finally {
// 关闭Session
session.close();
}
}
方案二:使用注解将SQL与接口进行映射。
使用注解的形式,接口对应的XML文件中。不写方法对于的SQL。在接口中的方法上使用注解的形式在括号中写向要的SQL,可以使用@Param将方法中的参数和SQL中的参数进行关联。需要注意的是,在.xml中没有写SQL时,在mybatis配置文件中也要进行配置。不然会说无法识别接口中的方法。
public interface UserMapper {
/**
* 显示所有用户
* @return
*/
@Select("SELECT * FROM user where id=#{Id}")
User getUserById(@Param("Id")Integer id);//使用@Param将方法参数与SQL中的参数进行关联
}
XML与注解:对于简单语句来说,注解使代码显得更加简洁,然而 Java 注解对于稍微复杂的语句就会力不从心并且会显得更加混乱。因此,如果你需要做很复杂的事情,那么最好使用 XML 来映射语句。
部分参考官方文档。