本文参照B站尚硅谷学习(刚刚入门,正在学习,***侵必删!***)
(先单独看xml配置)
首先创建数据库表(如下,在mybatis库下创建一个employee表)
这是文件目录结构:
(libs目录下导入mybatis包和mysql驱动包)
(conf目录下是需要的xml配置文件,本来conf和src是同级目录,但是这样main类无法访问到xml文件,我就放到src下了)
创建于数据库的表对应的Bean类。(getter和setter省略)
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;}
接下来是mybatis的全局配置文件,(即文件结构里的mybatis_config.xml)
执行结果
源码如下:
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="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--&-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="conf/employeeMapper.xml"/>
</mappers>
</configuration>
employeeMapper.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">
<mapper namespace="test.Employee">
<!-- namespace:名称空间 id :唯一标识 resultType:返回类型-->
<select id="test.Employee.selectEmploy" resultType="test.Employee">
select id,last_name lastName,email,gender from employee where id = #{id}
</select>
</mapper>
Main:
package com.company;
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 test.Employee;
import java.io.IOException;
import java.io.InputStream;
public class Main {
/**
* @throws IOException
* 1根据xml(全局配置文件)创建一个sqlsessionfactory对象
*/
public static void main(String[] args) throws IOException {
String resource = "conf/mybatis_config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
/**
* 2 获取sqlSession实例,直接执行已经映射的sql语句
* selectOne()参数含义
* @param statement Unique identifier matching the statement to use.
* @param parameter A parameter object to pass to the statement.
*/
SqlSession openSession= null;
try {
openSession = sqlSessionFactory.openSession();
Employee employee=openSession.selectOne("selectEmploy",1);
System.out.println(employee);
} catch (Exception e) {
e.printStackTrace();
}finally {
openSession.close();
}
}
}
问题汇总:
1、 xml配置文件要和main类在一个目录下,(还有其他解决办法),不然main类无法访问xml
2、 数据库驱动配置,似乎我目前只能写一个,首先遇到中英文“&”都不能识别。。未解决所以我暂时只写了报错的serverTimeZone,
(接口式编程改进)
新建一个映射接口: