Home > 类库下载 > java类库 > body text

Simple example of Mybatis

高洛峰
Release: 2016-11-02 10:36:08
Original
1906 people have browsed it

First create a new JavaWeb project and import the jar package that mybatis depends on. At the same time, Mybatis operates on the database, so we need to create a new table user in the database for demonstration.

After creating the new table, we also need to create the corresponding entity class User.java and add set and get methods:

public class User {
    private String username;
    private String password;
    private int age;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
Copy after login

In Mybatis, we need to create a mapping file userMapper.xml corresponding to the entity class:

<?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,namespace的值习惯上设置成包名+sql映射文件名)
 -->
<mapper namespace="com.mybatis.mapping.userMapper">
    <!-- 在select标签中编写查询的SQL语句,id属性值必须是唯一的
    使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
    -->
    <!-- 
        根据username查询得到一个user对象
     -->
    <select id="getUser" parameterType="java.lang.String" 
        resultType="com.mybatis.po.User">
        select * from user where username=#{username}
    </select>
    
       <delete id="deleteUser" parameterType="java.lang.String">
        delete from user where username=#{username}
    </delete>
</mapper>
Copy after login

Finally, we need to create a new configuration file config.xml for Mybatis and database connection under src, and import the above userMapper.xml. The code is as follows:

<?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.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test" />
                <property name="username" value="root" />
                <property name="password" value="" />
            </dataSource>
        </environment>
    </environments>
     <mappers>
        <!-- 注册userMapper.xml文件,resource为userMapper.xml所在目录-->
         <mapper resource="com/mybatis/mapping/userMapper.xml"/>
     </mappers>
</configuration>
Copy after login

The configuration database connection information here is not very different from Hibernate. Now we create a new Use a Test class to test it:

public class Test {

    public static void main(String[] args) throws IOException {
        //mybatis的配置文件
        String resource = "config.xml";
        //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
        InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //打开session
        SqlSession session = sessionFactory.openSession();
        /**
         * 映射sql的标识字符串
         *com.mybatis.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
         * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
         */
        String statement = "com.mybatis.mapping.userMapper.getUser";//映射sql的标识字符串
        //执行查询返回一个唯一user对象的sql
        User user = session.selectOne(statement,"username1");
        System.out.println(user.getUsername());
        String statement2="com.mybatis.mapping.userMapper.deleteUser";
        session.delete(statement2,user);
    }
}
Copy after login

Executing the selectOne method will return a user object (if you want to query multiple pieces of data, you can use selectList. This method will return a List object). We output the username of the user object in the console. Executing the delete method can directly delete a piece of data corresponding to the object, and whether the execution is successful can be judged based on the changes in the database. The following is the directory of my project, you can refer to it:

Simple example of Mybatis

The above is a simple example of Mybatis. Of course, in userMapper.xml, we can also use OGNL to generate dynamic sql statements. If you are interested, you can study it yourself.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template