新认识MyBatis

Mybatis
1.持久化
持久化,就是内存数据及硬盘数据状态的换
2.ORM思想
Object Relation Mapping 对象关联映射
3.MyBatis入门案例
3.1导入jar包
依赖
<!–MySQL配置–>
<dependency>
<groupId>MySQL</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
<!–MyBatis核心jar包–>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>

3.2修好布局

<?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"&gt;
<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/y2165″/>
<property name=”username” value=”root”/>
<property name=”password” value=”root”/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource=”org/mybatis/example/BlogMapper.xml”/>
</mappers>
</configuration>
3.3实体类
public class StudentInfo {
private Integer stuId;
private String stuName;
private Integer stuAge;
private Date stuDate;
}

3.4小配置
<?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"&gt;
<mapper namespace=”cn.happy.dao.IStudentInfoDAO”>
<select id=”findAll” resultType=”cn.happy.entity.StudentInfo”>
select * from studentinfo
</select>
</mapper>

个别个注意事项:
1.而得更新POM.xml文件中build节点
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>

2.若得在深布局中关系小布置文件
<mappers>
<mapper resource=”cn/happy/dao/IStudentInfoDAO.xml”/>
</mappers>

3.5 写测试类
3.5.1 String path=”大布局的里程径名”;
InputStream is=Resources.getResourcesAsStream(path);
SessionFactory factory=new SessionFactoryBuilder().build(is);
SqlSession session=factory.openSession();

结论:

  1. 注意小布置的命名空间的名号

4.号的施用
<typeAliases>
<!–<typeAlias type=”cn.happy.entity.StudentInfo”
alias=”StudentInfo”></typeAlias>–>
<!–将该包中之大概类型 StudentInfo作为类的别名–>
<package name=”cn.happy.entity”></package>
</typeAliases>

5.getMapper() 动态代理数据
class<T> 类型的种
is = Resources.getResourceAsStream(path);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session=factory.openSession();
IStudentInfoDAO dao = session.getMapper(IStudentInfoDAO.class);
StudentInfo info = dao.getStudentById(3);
System.out.println(info.getStuName());

网站地图xml地图