• Mybatis之基础应用小结以及IntelliJ IDEA目录结构的一些小问题


    IntelliJ IDEA 目录结构的一些小问题

    【Mybatis 之基础应用小结】

     1、不管怎么样,先建立一个简单的MySQL数据表,如下所示

    2、接下来要做的事情就是通过Mybatis对数据表进行基础的增删查改,写好bean以及打算实现的方法

    import java.util.List;
    
    public class PersonDAO {
    
        public void savePerson(Person person) {
    
        }
    
        public void removePersonByName(String name) {
    
        }
    
        public void removePersonByAge(int age) {
    
        }
    
        public List<Person> listPersonByName() {
            return null;
        }
    
        public List<Person> listPersonByAge() {
            return null;
        }
    
        public void updatePersonByName() {
            
        }
    }

    3、在写代码之前,先添加必要的依赖包,

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.0.4</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.1</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>

    4、要实现上述罗列的方法的第一步就是获取数据表所在数据库的连接,

    把配置文件COPY进来,编辑好连接所需要的信息,(mappers先注释掉,顺手把log4j的配置文件也丢进来

    在这之前先把项目分好层次,

     

    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>
    
      <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC">
            <property name="" value=""/>
          </transactionManager>
          <dataSource type="UNPOOLED">
            <property name="driver" value="org.gjt.mm.mysql.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/my_test"/>
            <property name="username" value="root"/>
            <property name="password" value="19971019"/>
          </dataSource>
        </environment>
      </environments>
     
      <!--<mappers>-->
        <!--<mapper resource="????"/>-->
      <!--</mappers>-->
      
    </configuration>

    log4j.properties

    log4j.rootLogger=DEBUG, MyConsole 
    log4j.appender.MyConsole=org.apache.log4j.ConsoleAppender
    log4j.appender.MyConsole.layout=org.apache.log4j.PatternLayout
    log4j.appender.MyConsole.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
    log4j.logger.org.apache=INFO

    5、我们的最终目的是得到SqlSession类对象,以便通过该对象执行SQL语句,在此之前需要建立SqlSessionFactory,

    我将这段代码独立地放在db层下,如下所示:

    package db;
    
    import java.io.IOException;
    import java.io.Reader;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    /**
     * 访问数据库类
     */
    public class DBAccess {
        public SqlSession getSqlSession() throws IOException {
            Reader reader = Resources.getResourceAsReader("Configuration.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;
        }
    }

    这样就可以方便地获得SqlSession类对象了。

    6、真正开始实现personDAO,先把模板COPY到类底下

        private static DBAccess dbAccess = null;
        private static SqlSession sqlSession = null;
    
        static {
            dbAccess = new DBAccess();
            try {
                sqlSession = dbAccess.getSqlSession();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void finalize() throws Throwable {
            sqlSession.close();
            super.finalize();
        }

    ( 有错。线程不安全)

    创建 person.xml 并把模板COPY进来略做修改

    <?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="Person">
    
        <resultMap type="bean.Person" id="PersonResult">
            <result column="NAME" jdbcType="VARCHAR" property="name"/>
            <result column="AGE" jdbcType="INTEGER" property="age"/>
        </resultMap>
    
    </mapper>

    修改Configuration.xml 中的 mapper

      <mappers>
        <mapper resource="sqlxml/Person.xml"/>
      </mappers>

    接下来的节奏就是 person.xml --> PersonDAO.java --> 测试 --> person.xml --> PersonDAO.java --> 测试 --> person.xml --> PersonDAO.java --> 测试 --> person.xml --> PersonDAO.java --> 测试 --> person.xml --> PersonDAO.java --> 测试 --> person.xml --> PersonDAO.java --> 测试 --> .... 一个一个方法写下来。在SQL语句中如何获取特定类型的参数值 可以参考 通过自动回复机器人学Mybatis:OGNL+log4j.properties 里面的图片

    7、完成之后是这个样子的,

    person.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="Person">
    
        <resultMap type="bean.Person" id="PersonResult">
            <result column="NAME" jdbcType="VARCHAR" property="name"/>
            <result column="AGE" jdbcType="INTEGER" property="age"/>
        </resultMap>
    
        <insert id="savePerson" parameterType="bean.Person">
             INSERT INTO person VALUES (#{name}, #{age})
        </insert>
    
        <delete id="removePersonByName" parameterType="String">
            DELETE FROM person WHERE name='${_parameter}'
        </delete>
    
        <delete id="removePersonByAge" parameterType="int">
            DELETE FROM person WHERE name=${_parameter}
        </delete>
    
        <select id="listPersonByName" parameterType="String" resultMap="PersonResult">
            SELECT name, age FROM person WHERE name='${_parameter}'
        </select>
    
        <select id="listPersonByAge" parameterType="int" resultMap="PersonResult">
            SELECT name, age FROM person WHERE age=${_parameter}
        </select>
    
        <update id="updatePersonByName" parameterType="bean.Person">
            UPDATE person SET age=${age} WHERE name='${name}'
        </update>
        
    </mapper>

    personDAO.java

    package dao;
    
    import bean.Person;
    import db.DBAccess;
    import org.apache.ibatis.session.SqlSession;
    
    import java.io.IOException;
    import java.util.List;
    
    public class PersonDAO {
        private static DBAccess dbAccess = null;
        private static SqlSession sqlSession = null;
    
        static {
            dbAccess = new DBAccess();
            try {
                sqlSession = dbAccess.getSqlSession();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void finalize() throws Throwable {
            sqlSession.close();
            super.finalize();
        }
    
        public static void main(String[] args) {
            Person person = new Person();
            person.setName("小王");
            person.setAge(23);
    
            PersonDAO personDAO = new PersonDAO();
            personDAO.savePerson(person);
            // personDAO.removePersonByName("小王");
            // personDAO.removePersonByAge(23);
            System.out.println(personDAO.listPersonByName("小王"));
            for (Person p : personDAO.listPersonByAge(19)) {
                System.out.println(p);
            }
            personDAO.updatePersonByName("小王", 0);
        }
    
        public void savePerson(Person person) {
            sqlSession.insert("Person.savePerson", person);
            sqlSession.commit();
        }
    
        public void removePersonByName(String name) {
            sqlSession.delete("Person.removePersonByName", name);
            sqlSession.commit();
        }
    
        public void removePersonByAge(int age) {
            sqlSession.delete("Person.removePersonByAge", age);
            sqlSession.commit();
        }
    
        public List<Person> listPersonByName(String name) {
            return sqlSession.selectList("Person.listPersonByName", name);
        }
    
        public List<Person> listPersonByAge(int age) {
            return sqlSession.selectList("Person.listPersonByAge", age);
        }
    
        public void updatePersonByName(String name, int age) {
    
            Person person = new Person();
            person.setName(name);
            person.setAge(age);
    
            sqlSession.update("Person.updatePersonByName", person);
            sqlSession.commit();
        }
    }

     这样写貌似会造成线程不安全,单个用户多次刷新的时候

    【IntelliJ IDEA目录结构的一些小问题】

     IntelliJ IDEA 的目录结构和 eclipse 的目录结构有那么一点不同,

    如果在 IntelliJ IDEA 中采取 eclipse 中的方式来读取Mybatis配置文件是要出错的!(反之亦然

    eclipse 的根目录是 src

    而  IntelliJ IDEA 则把各类文件分了类,管你怎么弄,类别不对就是读不到。。。

    我们需要自定义各种类型文件的根目录

     

    为了顺利读到配置文件,个人采取的方式是把 config 文件直接分离出来并设置为 Sources Root

    然后通过 Copy Relative Path 来得到所需配置文件的路径

    在本例中结果是这样的,相对路径非常简洁

  • 相关阅读:
    python框架之Django(2)-简单的CRUD
    python框架之Django(1)-第一个Django项目
    实习进度13
    实习进度12
    实习进度11
    实习进度10
    学习进度08
    毕设进度07
    毕设进度06
    毕设进度05
  • 原文地址:https://www.cnblogs.com/xkxf/p/7137824.html
Copyright © 2020-2023  润新知