mybatis入门和配置

一、导入相关jar包和驱动包。mybatis参考文档https://mybatis.org/mybatis-3/zh/index.html

二、新建Source Folder文件夹,放置db.properties数据库配置、log4j.properties日志配置、mybatis-config.xml等配置文件

  1、db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test1
username=root
password=123456

  2、log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  3、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" 的内容必须匹配
   "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,
   plugins?,environments?,databaseIdProvider?,mappers?)"。 -->
  
  <!-- 主配置的入口 -->
  <configuration>
          <!-- 加载properties文件 -->
          <properties resource="db.properties"></properties>
          <settings>
              <!-- 配置日志的详细信息 -->
              <setting name="logImpl"  value="LOG4J"/>
          </settings>
          <!--配置别名 -->
          <typeAliases>
              <!--  一个一个配置,不推荐-->
              <!--<typeAlias type="com.gx.domain.User" alias="User" />-->
              <!--  批量配置包里面的所有实体类-->
              <package name="com.gx.domain"/>
          </typeAliases>
  
          <!--配置数据库连接,default默认使用哪一个数据库连接  -->
          <!-- environments指mybatis可以配置多个环境,default指向默认的环境,每个sqlSessionFactory对应一个环境 environment-->
          <environments default="mysql">
                  <environment id="mysql">
                          <!--事务管理,使用JDBC的事务  -->
                          <!--JDBC[重点],直接使用JDBC的提交和回滚功能,它依赖于从数据源获得连接来管理事务的生命周期  -->
                          <!--MANAGED,这个配置基本上什么都不做,它从不提交或者回滚一个连接的事务,而是容器(如spring)来管理事务的生命周期  -->
                          <transactionManager type="JDBC"></transactionManager>
                          <!--数据源类型  
                          1、UNPOOLED[了解]实现只是在每次需要的时候简单的打开和关闭连接
                          2、POOLED[重点]实现了缓存JDBC连接对象,用于避免每次创建新的数据库连接时初始化和进行认证,加快程序响应,
                              并发WEB应用通常通过这种做法来获得快速响应
                          3、JNDI[知道]是为了准备与像spring或者应用服务器能够在外部或者内部配置数据源的容器一起使用,然后在JNDI上
                              下文中引用它-->
                          <dataSource type="POOLED">
                                  <property name="driver" value="${driver}"/>
                                <property name="url" value="${url}"/>
                                <property name="username" value="${username}"/>
                                <property name="password" value="${password}"/>
                          </dataSource>
                  </environment>
          </environments>
          <!-- 配置映射 -->
          <mappers>
                  <mapper resource="com/gx/mapping/UserMapper.xml"/>
                  <!-- 注解的时候使用class -->
                  <!--<mapper class="" />-->
          </mappers>
  </configuration>

三、具体代码如下

  1.User实体类

public class User {
        private Integer id;
        private String name;
        private String address;
        private Date birthday;
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        public Date getBirthday() {
            return birthday;
        }
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + ", address=" + address + ", birthday=" + birthday + "]";
        }
        public User() {
            super();
            // TODO Auto-generated constructor stub
        }
        public User(Integer id, String name, String address, Date birthday) {
            super();
            this.id = id;
            this.name = name;
            this.address = address;
            this.birthday = birthday;
        }
        public User(String name, String address, Date birthday) {
            super();
            this.name = name;
            this.address = address;
            this.birthday = birthday;
        }
        

}

  2.UserMapper接口

public interface UserMapper {
	public void add(User user);
	public void update(User user);
	public void delete(Integer id);
	public User selectById(Integer id);
	public List<User> selectAll();
}

  3.UserMapping.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">
  <!-- namespace和Mapper接口类名字一样 -->
<mapper namespace="com.gx.mapper.UserMapper">
    <!-- 添加 -->
    <!-- id对应接口里面的方法名,不能重复 -->
    <!-- parameterType:参数类型 -->
    <!--<parameterMap type="com.gx.domain.User" id="myuser">
            <parameter property="name" javaType="java.lang.String"/>
            <parameter property="address" javaType="java.lang.String"/>
            <parameter property="birthday" javaType="java.lang.String"/>
    </parameterMap> -->
    <!-- parameterMap:定义参数的map类型 方法里面的传参必须是map,要在mapper里面创建一个id=myuser的节点 -->
    <!-- userGeneratedKeys="true" 是否使用自动增长,默认为true-->
    <!-- parameterType和parameterMap只能存在一个 -->
    <insert id="add" parameterType="com.gx.domain.User"  >
        insert into user(name,address,birthday) values(#{name},#{address},#{birthday})
    </insert>
    <!-- 修改 -->
    <!-- id对应接口里面的方法名,不能重复 -->
    <!-- parameterType:参数类型 -->
    <update id="update"  parameterType="com.gx.domain.User">
        update user set name=#{name},address=#{address},birthday=#{birthday} where id=#{id}
    </update>
    <!-- 删除 -->
    <!-- id对应接口里面的方法名,不能重复 -->
    <!-- parameterType:参数类型 ,如果是基本数据类型或String,可以不配置parameterType-->
    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id=#{value}
    </delete>
    <!-- 查询一个 -->
    <!-- id对应接口里面的方法名,不能重复 -->
    <!-- parameterType:参数类型 ,如果是基本数据类型或String,可以不配置parameterType-->
    <!-- resultType:返回值的类型 -->
    <select id="selectById" parameterType="java.lang.Integer" resultType="com.gx.domain.User">
        select * from user where id=#{value}
    </select>
    <!-- 查询所有 -->
    <!-- resultMap: 如果查询的结果集和实体的属性名不一致,那么要使用resultMap去处理-->
    <!-- resultType: 指定返回值的类型,保存查询的结果集合和实体的属性名一致-->
    <!-- resultMap和resultType只能使用其一 -->
    <resultMap type="com.gx.domain.User"  id="myRsMap">
        <id property="id"  column="uid"/>
        <result property="name"  column="uname"/>
        <result property="address"  column="add"/>
        <result property="birthday"  column="birth"/>
    </resultMap>
    <!--<select id="selectAll" resultMap="myRsMap"></select>-->
    <!-- User配置别名 -->
    <select id="selectAll" resultType="User" >
        select * from user
    </select>
</mapper>

  4.个人写的工具类,为了方便而已,MyBatisUtils.java

public class MyBatisUtils {
	static InputStream is=MyBatisUtils.class.getResourceAsStream("/mybatis-config.xml");
	
	//1.得到SQLSessionFactory
	static SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
	//得到session
	public static SqlSession openSession() {
		return factory.openSession();
	}
	//提交并关闭
	public static void closeSession(SqlSession session) {
		session.commit();
		session.close();
	}
}

  5.测试

public class Test {

	public static void main(String[] args) {

		SqlSession session = MyBatisUtils.openSession();
		//得到UserMapper的代理对象
		UserMapper userMapper = session.getMapper(UserMapper.class);
		System.out.println(userMapper.getClass().getSimpleName());
		User user2 = new User(1,"曹操", "魏国",new Date());
		userMapper.update(user2);
		MyBatisUtils.closeSession(session);
	}

}

四、xml配置文件中每个字段的用法已经讲述清楚,为了避免代码冗余,将sqlSessionFactory封装了,这一套应该是最方便快捷的使用方法。

猜你喜欢

转载自www.cnblogs.com/97guoxiang/p/12763612.html