一.mybatis的使用
1.原始的dao开发,dao接口+dao实现类
2.使用mapper接口,
mapper接口相当于dao的接口
配置文件分成两块(全局的配置文件,映射文件)
mybatis的优势一部分是支持动态sql
mybatis.xml头文件内容用于识别整个xml文件是否出错,如下:
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
以下是mapper的头文件:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
开始使用mybatis
首先需要下载mybatis数据包
配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="db.profile"></properties><!-- resource:资源property:性质、属性,在这个文件上写jdbc --> <environments default="own"> <environment id="own"> <transactionManager type="jdbc"></transactionManager> <dataSource type="POOLED"><!-- 表示已经缓存了 --> <property name="driver" value="${driver}"></property> <property name="url" value="${url}"></property> <property name="username" value="${username}"></property> <property name="password" value="${password}"></property> </dataSource> </environment> </environments> </configuration>
映射文件:
<?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="xxxx.uuuu"> <select id="sele" parameterType="int" resultType="nf.entity.User"> select * from tt4 where id=#{id}; </select> </mapper>
使用dao层调用这个mybaties所有文件
package nf.dao;
import java.io.IOException;
import java.io.InputStream;
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 nf.entity.User;
public class UserDaoImpl implements UserDao {
@Override
public User getUserById(int i) {
try {
InputStream inputStream = Resources.getResourceAsStream("/sqlMapConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sessionFactory.openSession();
User user = session.selectOne("nf.entity.getUserById", i);//mapper的空间名加id(方法)名,所传的值
session.close();
return user;
} catch (IOException e) {
System.out.println("异常:"+e.getMessage());
e.printStackTrace();
return null;
}
}
}
就可以用servelt调用这个dao层了
返回值映射:有多少个列就设置多少个result,id为主键
写typeAliases会使mapper自动扫描你定义的javabean
1.2使用java代替session.select()的方法
注意:这个空间名要和放java类的包名一样
1.3.使用标识符来代替mapper的xml文件
package mappers; /** 实现类,不需要程序员写,是MyBatis自动在内存中完成*/ import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import entity.User; @Mapper public interface mapper { @Select("select * from user1") @Results({ @Result(id=true,property="id",column="id"), @Result(property="userName",column="name"), @Result(property="sex",column="sex") }) List<User> getall(); }
下面的mapper扫描也需要修改为class