Mybatis是操作数据库的一个框架,最大的有点是将sql与程序相互分离。可以将sql语句映射到接口中的方法。支持动态sql。
Mybatis配置:配置连接的数据库,可以一次配多个。但默认只能选一个
mybatis-config.xml
<configuration>
<!--引入properties配置文件-->
<properties resource="app.properties"/>
<!--开启驼峰命名的映射-->
<settings >
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--定义别名-->
<typeAliases>
<typeAlias type="com.pojo.Student" alias="Student"/>
<package name="com.pojo"/>
</typeAliases>
<!--配置连接的数据库环境,设置默认使用的数据库环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<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>
<!--配置映射,写sql的文件-->
<mappers>
<mapper resource="com/mapper/StudentsMapper.xml"/>
</mappers>
</configuration>
StudentsMapper.xml文件:参数类型也可以是对象类型的
<mapper namespace="com.mapper.StudentMapper">
<select id="selectStudent" parameterType="int" resultType="Student">
select * from students where stu_id=#{id}
</select>
</mapper>
main方法:
public class Main {
public static void main(String[] args) throws Exception{
String resource= "mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=sqlSessionFactory.openSession();
Student student=session.selectOne("com.mapper.StudentMapper.selectStudent",1);
System.out.println(student);
}
}
通过配置文件mybatis-config.xml和sqlSessionFactoryBuilder来构建一个sqlSessionFactory,该类相当于一个数据库的连接池。接下来通过连接池来获得连接对象sqlSession。通过连接对象来执行sql语句。
将StudentsMapper.xml中的sql语句映射到接口中的方法,将接口全限定名和上述文件的namespace属性保持一致,接口中的方法和SQL语句的id保持一致即可。
接口:
public interface StudentsMapper {
public Students selectStudent(int id);
}
main方法:
//为接口生成一个实例对象,通过这个对象来操作数据库。
StudentsMapper studentsMapper=session.getMapper(StudentsMapper.class);
Students stu=studentsMapper.selectStudent(1);
在数据库中插入一条记录:
StudentsMapper.xml
<insert id="insertStudent" parameterType="com.pojo.Students">
insert into students(name, email, phone) values(#{name},#{email},#{phone})
</insert>
接口:
public void insertStudent(Students students);
main方法:
StudentsMapper studentsMapper=session.getMapper(StudentsMapper.class);
Students stu=new Students("lisi","abcdef@163.com","13468667152");
studentsMapper.insertStudent(stu);
session.commit();
查询出来的结果集之所以能够映射到对象中,是因为,数据库中的列名和实体类中的属性名存在对应关系。这种关系可以是两个名称一致;也可以是从stu_id到stuId;同样也可以自定义resultMap来映射。
补充
<typeAliases>
<package name="com.pojo"/>
</typeAliases>
加入以上代码后,可以用teacher或Teacher来代替com.pojo.Teacher。也可以在类上添加@Alias(“tea”)。用tea或Tea来代替com.pojo.Teacher。在实体类上添加别名时,要在配置文件中添加以上代码。
| 上一篇 |
---The End---
| 下一篇 |
本文深入探讨了MyBatis框架的使用方法,包括配置数据库连接、动态SQL支持、对象关系映射以及如何通过接口调用执行SQL语句。介绍了如何在MyBatis中配置别名、映射实体类和执行CRUD操作。
2662

被折叠的 条评论
为什么被折叠?



