其他分享
首页 > 其他分享> > Mybatis(class、xml、mapper)

Mybatis(class、xml、mapper)

作者:互联网

Mybatis 使用 Class、xml实现操作数据库(基础的javaProject)

jar包:mybatis-3.5.2.jar / mysql-connector-java-5.1.47.jar

目录:src/mybatis/dao

创建mybatis-config.xml 作用:数据库配置

NewsMapper.xml 作用:sql语句

mybatis-config.xml(配置数据库)

<?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="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/maven?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mybatisClass/dao/NewsMapper.xml"/>
    </mappers>
</configuration>

NewsMapper.xml(sql语句)

<?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">
<!-- namespace对应接口文件 -->
<mapper namespace="mybatisClass.dao.NewsMapper">
    <!-- id是接口类里的方法名 -->
    <!-- resultType是返回实体类型(带包名) -->
    <select id="selectUser">
        select * from user where id = #{id}
    </select>

    <insert id="insertUser">
        insert into user values(#{id},#{password})
    </insert>
</mapper>

MybatisDrill(创建工程,创建sqlsession,调用sql)

package mybatisClass;
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.InputStream;
import java.util.HashMap;

public class MybatisDrill {
    private static SqlSessionFactory sqlSessionFactory;

    public static void main(String[] args) throws Exception{
        String resource = "mybatisClass/dao/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        selectUser(sqlSession);
    }

    public static void selectUser(SqlSession sqlSession){
        HashMap<String,String> news = new HashMap<String,String>();
        news.put("id","news");
        news.put("password","520520");
        int n = sqlSession.insert("mybatisClass.dao.NewsMapper.insertUser",news);
        sqlSession.commit();
        sqlSession.close();
    }
}

实现的效果就是在数据库的User表中插入了一行数据

 

标签:xml,mybatis,sqlSession,import,Mybatis,news,apache,class
来源: https://www.cnblogs.com/loveDonkey/p/16047233.html