public class MyBatisDemo {
public static void main(String[] args) throws IOException {
//1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
String resource = "mybatis-config.xml";
//字节输入流
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建共存对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2. 获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//3. 使用sqlSession的selectList执行sql
List<User> users = sqlSession.selectList("test.selectAll"); //参数是一个字符串,该字符串必须是映射配置文件的namespace.id
System.out.println(users);
//4. 释放资源
sqlSession.close();
}
}
解决SQL映射文件的警告提示:
在Idea中配置MySQL数据库连接。
new directory --com/itheima/mapper/
MybatisUtil
`
//Mybatis工具类
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
//静态代码块
static {
try {
//1.指定mybatis核心配置文件的路径
String resource = "mybatis-config.xml";
//2.使用mybatis工具类Resources调用静态方法加载核心配置文件,获取字节输入对象
InputStream inputStream = Resources.getResourceAsStream(resource);
//3.创建一个SqlSession工厂类SqlSessionFactory的对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
//构造方法私有
private MybatisUtil(){}
//定义静态方法,获取SqlSession接口对象
public static SqlSession getSqlSession() throws IOException {
//获取SqlSession接口对象并返回
return sqlSessionFactory.openSession();
}
//定义静态方法,释放资源
public static void close(SqlSession sqlSession) {
sqlSession.close();
}
}
//测试品牌数据的增删改查
public class Demo01BrandTest {
//测试查询所有品牌数据
@Test
public void testSelectAll() throws IOException {
//1.使用Mybatis工具类获取SqlSession对象
SqlSession sqlSession = MybatisUtil.getSqlSession();
//2.使用SqlSession对象获取接口代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//3.使用接口代理对象调用方法完成增删改查的操作,获取结果
List<Brand> brandList = brandMapper.selectAll();
//4.处理结果数据
System.out.println(brandList);
//5.释放资源
MybatisUtil.close(sqlSession);
}
} `
属性名pojo 与sql不一样
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
映射文件内容
<!--
resultMap标签: 是用来完成结果对象封装的
id: 唯一标识
type: 封装结果的类型,可以写别名
-->
<resultMap id="brandMap" type="brand">
<!--
id标签: 作用是进行主键配置的
column属性: 写的sql字段名
property属性: 类的属性名
-->
<id column="id" property="id"/>
<!--
result标签: 作用是指定sql字段名和类中属性名的对应关系的
注意: 只针对id以外的标签
column属性: 写的sql字段名
property属性: 类的属性名
-->
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
<!--其它字段名和属性名相同的内容,可以不配,会自动进行映射-->
</resultMap>
<!--
演示resultMap标签的使用
把resultType属性替换成resultMap,属性值写resultMap标签的id值
-->
<select id="selectAll4" resultMap="brandMap">
select id, brand_name, company_name, ordered, description, status
from tb_brand
</select>