当前位置:   article > 正文

MyBatis框架基础在eclipse中使用的最全教程_eclipse mbatis

eclipse mbatis

它封装了JDBC操作的繁琐操作,对JDBC进行了封装,它相比传统的JDBC访问数据库,性能更加优异,具有高度的灵活性、可优化性和易于维护等特点,我们只需要关注 sql语句本身, 而不需要花费精力去处理加载驱动、创建连接、创建 statement 等繁杂的过程。

配置MyBatis

  1. 下载MyBatis包,下载地址https://github.com/mybatis/mybatis-3/releases
  2. 我下载的版本是3.5.5,下载后解压,解压之后的目录是这样的
  3. 找到lib目录,把lib目录里的jar包全部拷贝到java项目中
  4. 导入数据库驱动包,下载地址https://dev.mysql.com/downloads/connector/j/
  5. 这时候我们的工程目录下是这样的
  6. 找到我们刚才下载的Mybatis包,并解压
  7. 解压之后,进入这个目录mybatis-3.5.5/mybatis-3.5.5/org/apache/ibatis/builder/xml,找到如下两个文件
  8. 在Eclipse中配置mybatis-3-config.dtd和mybatis-3-mapper.dtd,目的是让后面的xml文件的时候有标签提示
  9. 在src目录下创建jdbc.properties
    1. jdbc.driver=com.mysql.cj.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/你的数据库名?characterEncoding=UTF-8
    3. jdbc.username=你的数据库登录账号
    4. jdbc.password=你的数据库登录密码
  10. 在src目录下创建sqlMapConfig.xml
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <!-- 配置全局配置文件 -->
    6. <configuration>
    7. <!-- 引入jdbc.properties -->
    8. <properties resource="jdbc.properties" />
    9. <environments default="develop">
    10. <!-- 配置开发环境和正式环境 -->
    11. <environment id="develop">
    12. <!-- 必须先配置事务管理方式 type:JDBC 把事务交给JDBC来管理 type:MANAGED 自己管理事务 -->
    13. <transactionManager type="JDBC"></transactionManager>
    14. <!-- 其次配置数据库连接池(数据源) POOLED:使用连接池(数据源),推荐 UNPOOLED:不使用 JNDI:已经过时 -->
    15. <dataSource type="POOLED">
    16. <property name="driver" value="${jdbc.driver}" />
    17. <property name="url" value="${jdbc.url}"/>
    18. <property name="username" value="${jdbc.username}" />
    19. <property name="password" value="${jdbc.password}" />
    20. </dataSource>
    21. </environment>
    22. <!-- <environment id=""> </environment> -->
    23. </environments>
    24. <mappers>
    25. <mapper resource="com/tedu/pojo/EmpMapper.xml" />
    26. </mappers>
    27. </configuration>
  11. 在src目录下创建log4j.properties,目的是让控制台看到日志
    1. # Global logging configuration
    2. log4j.rootLogger=DEBUG, stdout
    3. # Console output...
    4. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    5. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    6. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
  12. 然后在src目录下创建如下几个类
  13. 稍等我们来解释各个类的作用及含义,我在本地创建了一张表,如下:
  14. People是一个简单的bean类
    1. package com.tedu.pojo;
    2. public class People {
    3. //声明私有属性
    4. private Integer id;
    5. private String name;
    6. private String gender;
    7. private String birthday;
    8. private String job;
    9. private String salary;
    10. private String bonus;
    11. private String home;
    12. private String pass;
    13. public String getPass() {
    14. return pass;
    15. }
    16. public void setPass(String pass) {
    17. this.pass = pass;
    18. }
    19. public Integer getId() {
    20. return id;
    21. }
    22. public void setId(Integer id) {
    23. this.id = id;
    24. }
    25. public String getName() {
    26. return name;
    27. }
    28. public void setName(String name) {
    29. this.name = name;
    30. }
    31. public String getGender() {
    32. return gender;
    33. }
    34. public void setGender(String gender) {
    35. this.gender = gender;
    36. }
    37. public String getBirthday() {
    38. return birthday;
    39. }
    40. public void setBirthday(String birthday) {
    41. this.birthday = birthday;
    42. }
    43. public String getJob() {
    44. return job;
    45. }
    46. public void setJob(String job) {
    47. this.job = job;
    48. }
    49. public String getSalary() {
    50. return salary;
    51. }
    52. public void setSalary(String salary) {
    53. this.salary = salary;
    54. }
    55. public String getBonus() {
    56. return bonus;
    57. }
    58. public void setBonus(String bonus) {
    59. this.bonus = bonus;
    60. }
    61. public String getHome() {
    62. return home;
    63. }
    64. public void setHome(String home) {
    65. this.home = home;
    66. }
    67. //提供toString方法
    68. @Override
    69. public String toString() {
    70. return "Emp [id=" + id + ", name=" + name + ", job=" + job + ", salary=" + salary + "]";
    71. }
    72. }
  15. PeopleMapper.xml
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <!-- namespace现在配置的是包路径,以后这里配置成接口的全路径 -->
    6. <mapper namespace="com.tedu.dao.PeopleMapper">
    7. <!-- 优化内容1:提取公共查询列的语句,需要的地方通过<include refid="columns"></include>来替换 -->
    8. <sql id="columns">id,name,salary</sql>
    9. <!-- 查询所有员工信息,返回list<People>集合, 查询结果返回java对象,再把这些对象封装到一个集合中,resultType指定结果类型。表示将查询结果封装到People对象中 -->
    10. <select id="selectAll" resultType="com.tedu.pojo.People">
    11. select
    12. <include refid="columns"></include>
    13. from people
    14. </select>
    15. <!-- 新增数据 -->
    16. <update id="insert">insert into people
    17. values(null,'马化腾','男','1978-02-03','开淘宝的','500','700','河北',123)
    18. </update>
    19. <!-- 新增数据 -->
    20. <update id="insertdata">insert into people
    21. values(null,#{name},#{gender},#{birthday},#{job},#{salary},#{bonus},#{home},#{pass})
    22. </update>
    23. <!-- 修改数据 -->
    24. <update id="update">update people set salary='5000' where name='马云'
    25. </update>
    26. <!-- 修改数据 -->
    27. <update id="updatedata">update people set salary=#{salary} where name=#{name}
    28. </update>
    29. <!-- 删除数据 -->
    30. <update id="delete">delete from people where name='马化腾'</update>
    31. <!-- 删除数据 -->
    32. <update id="deletedata">delete from people where name=#{name}</update>
    33. <!-- 查询单个数据,必须指定类型 -->
    34. <select id="selectOne" resultType="com.tedu.pojo.">
    35. select
    36. <include refid="columns"></include>
    37. from people where
    38. id=#{id}
    39. </select>
    40. <!-- 查询特定条件区间的数据 -->
    41. <select id="selectOnly" resultType="com.tedu.pojo.People">
    42. select
    43. <include refid="columns"></include>
    44. from people where
    45. salary between #{smallSalary} and #{bigSalary}
    46. </select>
    47. <!-- 查询特定列的数据 -->
    48. <select id="selectSomeColumn" resultType="com.tedu.pojo.People">select ${columns} from
    49. people
    50. </select>
    51. <!-- 模糊查询 -->
    52. <select id="selectLikes" resultType="com.tedu.pojo.People">select ${columns} from
    53. people where name like '%${p_name}%'</select>
    54. <!-- 根据if标签进行条件查询 动态sql -->
    55. <select id="select_if" resultType="com.tedu.pojo.People">
    56. select * from people
    57. <if test="p_name!=null">where name like '%${p_name}%'</if>
    58. </select>
    59. <!-- where和if标签结合使用 动态sql -->
    60. <select id="select_where_if" resultType="com.tedu.pojo.People">
    61. select * from people
    62. <where>
    63. <if test="smallSalary!=null">salary>#{smallSalary}</if>
    64. <if test="bigSalary!=null">and
    65. salary<![CDATA[<]]>#{bigSalary}
    66. </if>
    67. </where>
    68. </select>
    69. <!-- set标签 动态sql -->
    70. <update id="update_set">
    71. update people
    72. <set>
    73. <if test="home!=null">home=#{home} where name=#{name}</if>
    74. </set>
    75. </update>
    76. <!-- foreach遍历 item="ids"表示接收参数的变量 -->
    77. <update id="delete_array">
    78. delete from people where id in
    79. <foreach collection="array" open="(" separator="," close=")"
    80. item="ids">#{ids}</foreach>
    81. </update>
    82. </mapper>
  16. PeopleMapper.java
    1. package com.tedu.dao;
    2. import java.util.List;
    3. import com.tedu.pojo.People;
    4. /**
    5. * 1,EmpMapper.xml对应的接口
    6. * 2,接口中的方法名要和EmpMapper.xml中查询语句的id保持相同
    7. * @author sujianda
    8. *
    9. */
    10. public interface PeopleMapper {
    11. /**
    12. * 查询所有信息
    13. */
    14. public List<People> selectAll();
    15. /**
    16. * 根据id查询某一个员工
    17. */
    18. public People selectOne(int id);
    19. }
  17. MyBatisInterfaceTest测试类
    1. package com.tedu.mybatis;
    2. import java.io.IOException;
    3. import java.io.InputStream;
    4. import java.util.List;
    5. import org.apache.ibatis.io.Resources;
    6. import org.apache.ibatis.session.SqlSession;
    7. import org.apache.ibatis.session.SqlSessionFactory;
    8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    9. import org.junit.Test;
    10. import com.tedu.dao.PeopleMapper;
    11. import com.tedu.pojo.People;
    12. public class MyBatisInterfaceTest {
    13. public static void main(String[] args) throws IOException {
    14. //读取核心配置文件sqlMapConfig.xml,getResourceAsStream获取资源作为流
    15. InputStream in=Resources.getResourceAsStream("sqlMapConfig.xml");
    16. //通过配置信息获取SqlSessionFactory对象
    17. SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
    18. //通过工厂获取SqlSession对象,session线程不安全
    19. SqlSession session=factory.openSession();
    20. //getMapper(EmpMapper.class)返回的是一个EmpMapper实例,得到empMapper实例之后,再调用selectAll
    21. PeopleMapper empMapper=session.getMapper(PeopleMapper.class);
    22. List<People>list=empMapper.selectAll();
    23. //输出信息
    24. for (People emp : list) {
    25. System.out.println(emp.toString());
    26. }
    27. }
    28. @Test
    29. public void selectOne() throws IOException {
    30. InputStream in=Resources.getResourceAsStream("sqlMapConfig.xml");
    31. SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
    32. SqlSession session=factory.openSession();
    33. PeopleMapper empMapper=session.getMapper(PeopleMapper.class);
    34. People emp=empMapper.selectOne(1);
    35. System.out.println(emp.toString());
    36. }
    37. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/164161
推荐阅读
相关标签
  

闽ICP备14008679号