Java基础_MyBatis基础

mybatis是一个数据持久层(orm)框架
与传统的JDBC比较减少了61%的代码量
有2个文件1个接口
configuration.xml 全局配置文件
mapper.xml 核心配置文件 映射文件写sql语句的
sqlSession 接口

别名alias

在核心配置文件中

<typeAliases>
 <typeAlias  alias="stu" type="com.yunhe.bean.StudentBean"/>
</typeAliases>

如果数据库中列名与mybatis中不一致

  <mapper namespace="com.yunhe.dao.StudentDao">
   <select id="selectAll" resultType="stu">
   select id as id,name as name,age as age,sex as sex from student
   </select>

例子:
configuration.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 resource="java.properties"/>
 <!-- java类型的别名 -->
<typeAliases>
 <typeAlias  alias="stu" type="com.yunhe.bean.StudentBean"/>
 </typeAliases>
 <environments default="development">
 <environment id="development">
 <transactionManager type="JDBC"/>
 <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>
 <mappers>
 <mapper resource="stu.xml"/>
 </mappers>

 </configuration>

另还需要一个跟全局配置搭配的数据库信息
java.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student
jdbc.username=root
jdbc.password=1234

stu.xml(mapper映射文件)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <mapper namespace="com.yunhe.dao.StudentDao">
   <select id="selectAll" resultType="stu">
   select id as id,name as name,age as age,sex as sex from student
    </select>
  </mapper>

猜你喜欢

转载自blog.csdn.net/weixin_40197494/article/details/80670342