这里用注解开发 不用xml文件了,直接 接口方法上用注解即可,但是要在核心文件映射Mapper【下面讲解】,,例【查询数据库全部用户】:
package com.bihu.Service; import com.bihu.Bean.User; import com.bihu.Dao.UserMapper; 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.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class UserService { public static void main(String[] args) throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.findAll(); //查询全部用户 //下面打印 for (User item:userList) { System.out.println(item); } } }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> <!-- 导入的properties --> <properties resource="datasourceInfo.properties"></properties> <!-- 设置 --> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <!-- 别名 --> <typeAliases> <typeAlias type="com.bihu.Bean.User" alias="User"></typeAlias> <typeAlias type="com.bihu.Bean.Order" alias="Order"></typeAlias> <typeAlias type="java.util.List" alias="List"></typeAlias> </typeAliases> <!-- 插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageHelper"> <property name="dialect" value="mysql"/> </plugin> </plugins> <environments default="dev"> <environment id="dev"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/bihu/mapper/UserMapper.xml"></mapper> <!--这里使用注解查询也是要进行mapper映射的!!!!--> <mapper resource="com/bihu/mapper/OrderMapper.xml"></mapper> </mappers> </configuration>mybatis 配置文件 //主要看映射
package com.bihu.Dao; import com.bihu.Bean.User; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper { @Select("select * from user") List<User> findAll(); }UserMapper.interface //使用注解
UserMapper.xml 代码如下:
<?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.bihu.Dao.UserMapper"> <!--其实注解开发是通过映射 然后在这里写<select/> 标签的 上面namespace一定要对应接口 --> </mapper>
运行:
但是注解开发是不可以支持结果集ResultMap的,即字段名【JavaBean 和 数据库】不一样会报错。
其实他做的事情也很清楚了,就是注解把我们要写的标签映射了而已,,主要还是在 Sqlsession 里面做手脚 嘛.
本质:反射
底层:动态代理