Mybatis搭建

实现步骤:
1.导包
2.定义全局配置文件(核心配置文件)
*定义数据库连接信息(定义数据库连接池)

<---->
	   <properties resource="jdbc.properties"/>
<settings>
    <setting name="logImpl" value="log4j"/>
</settings>
<typeAliases>
        <package name="com.itheima.bean"/>
    </typeAliases>
<environments default="mysql">
    <environment id="mysql">
        <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>

​ *加载SQQL映射文件

<mappers>
    <mapper resource="映射文件名"/>
</mappers>

3编写SQL映射文件

	<mapper namespace="dao.dao">
    <select id="selects" resultType="domain.User" >
        select * from  user
    </select>
    <select id="select" resultType="domain.User" parameterType="int">
        select * from user where id=#{id}
    </select>
    <insert id="insert" parameterType="domain.User" >
        insert into user values (#{id},#{username},#{password})
    </insert>
    <update id="update" parameterType="domain.User">
        update user set username=#{username},password=#{password} where id =#{id}
    </update>
    <delete id="delete" parameterType="int">
        delete from user where id =#{int}
    </delete>
</mapper>

4.编写Java代码

​ *加载配置文件
​ *获取SQLSession

	public interface dao {
    List<User> selects();
    User select(int i);
    Integer insert(User user);
    Integer update(User user);
    Integer delete(int i);
}
	  public List<User> selects() {
        InputStream inp = null;
        SqlSession sqlSession = null;
        dao mapper = null;

        try {
            inp = Resources.getResourceAsStream("核心配置文件名称");
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inp);
            sqlSession = build.openSession(true);
            mapper = sqlSession.getMapper(dao.class);

        } catch (IOException e) {
            e.printStackTrace();
        }
        List<User> selects = mapper.selects();
        try {
            sqlSession.close();
            inp.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return selects;
    }
		

SqlSessionFactory
openSession() : 创建SQLSession并且默认不会自动提交事务
openSession(bool): 如果bool为true事务自动提交

Mapper标签
属性: namespace, 理解为包名

mybatis 映射文件自动生成 dao层实现类:
namespace=“dao层类全路径”
增删改查标签id=“方法名”

增删改查标签
id :方法名
resultType: 返回值类型
parameterType: 参数类型
sql语句接受参数用#{参数名}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值