01.基于IDEA搭建mybatis的MAVEN项目

01.基于IDEA搭建mybatis的MAVEN项目

<br/>

基础环境

<br/>

  • IDEA
    <br/>
  • MAVEN

<br/>

工程目录

<br/>
01.基于IDEA搭建mybatis的MAVEN项目

<br/>

mysql数据库

<br/>
01.基于IDEA搭建mybatis的MAVEN项目
<br/>

Maven Pom

添加mybatis以及mysql的依赖包

<!--pom xml配置内容-->
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mu</groupId>
    <artifactId>mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
    </dependencies>
    <build>
        <!--idea不会寻找src/main/java目录下的xml配置-->
        <resources>
           <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.tld</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.tld</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

创建各实体类以及mapper.xml文件

<br/>

  • User.java
package com.mu.mybatis.domain;

/**
 * Created by manunited1985 on 2017/11/23.
 */
public class User {
    private Integer userId;
    private String userName;
    private String userPassword;
    private String userEmail;

    public User(Integer userId, String userName, String userPassword, String userEmail) {
        this.userId = userId;
        this.userName = userName;
        this.userPassword = userPassword;
        this.userEmail = userEmail;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getUserEmail() {
        return userEmail;
    }

    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }

    @Override
    public String toString() {
        return "User [userId=" + userId + ", userName=" + userName
                + ", userPassword=" + userPassword + ", userEmail=" + userEmail
                + "]";
    }
}

<br/>

  • UserMapper.java
package com.mu.mybatis.mapper;
import com.mu.mybatis.domain.User;

/**
 * Created by manunited1985 on 2017/11/24.
 */
public interface UserMapper {
    public User selectUserById(Integer userId);
    public List<User> selectUserAll();
    public void insertUser(User user);
}

<br/>

  • UserMapper.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="com.mu.mybatis.mapper.UserMapper">
    <!--设置domain类和数据库中表的字段一一对应,注意数据库字段和domain类中的字段名称不致,此处一定要!-->
    <resultMap id="BaseResultMap" type="com.mu.mybatis.domain.User">
        <id column="USER_ID" property="userId" jdbcType="INTEGER" />
        <result column="USER_NAME" property="userName" jdbcType="CHAR" />
        <result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
        <result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />
    </resultMap>
    <!-- 查询单条记录 -->
    <select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
        SELECT * FROM t_user WHERE USER_ID = #{userId}
    </select>
         <!-- 查询所有记录 -->
    <select id="selectUserAll" resultMap="BaseResultMap">
        SELECT * FROM t_user
    </select>
     <!-- 插入单条记录 -->
    <insert id="insertUser" parameterType="com.mu.mybatis.domain.User">
        insert into t_user (USER_ID,USER_NAME,USER_PASSWORD,USER_EMAIL)
        values (#{userId},#{userName},#{userPassword},#{userEmail})
    </insert>
</mapper>

<br/>

  • Main.java
package com.mu.mybatis;

import com.mu.mybatis.domain.User;
import com.mu.mybatis.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by manunited1985 on 2017/11/23.
 */
public class Main {

    public static void main(String[] args) throws IOException {

        SqlSession session = null;

        try {
            // 读取配置信息
            String resource = "application.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

            // 选择不同的环境
            String env = "product";
            SqlSessionFactory factory = builder.build(inputStream,env);

            // 产生SqlSession对象
            session = factory.openSession();
            System.out.println(session);

            // 获取映射对象            
            UserMapper userMapper = session.getMapper(UserMapper.class);

            // 获取id为1的账户
            User user = userMapper.selectUserById(1);
            System.out.println(user);

            // 获取所有账户
            List<User> arrayList = userMapper.selectUserAll();
            System.out.println(arrayList);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (session != null)
                // 关闭连接
                session.close();
        }

    }
}

<br/>

数据库配置 jdbc.properties

jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc/:mysql/://127.0.0.1/:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc_username=root
jdbc_password=123456

<br/>

应用配置application.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>
    <properties resource="jdbc.properties"></properties>
    <environments default="development">
        <!--配置不同的环境下的数据源-->
        <!--开发模式下-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc_driver}"/>
                <property name="url" value="${jdbc_url}"/>
                <property name="username" value="${jdbc_username}"/>
                <property name="password" value="${jdbc_password}"/>
            </dataSource>
        </environment>
        <!--生产模式下-->
        <environment id="product">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc_driver}"/>
                <property name="url" value="${jdbc_url}"/>
                <property name="username" value="${jdbc_username}"/>
                <property name="password" value="${jdbc_password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/mu/mybatis/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

<br/>

运行结果

org.apache.ibatis.session.defaults.DefaultSqlSession@454b70a9
User [userId=1, userName=xiaoming, userPassword=123456, userEmail=x@sina.com]
[User [userId=1, userName=xiaoming, userPassword=123456, userEmail=x@sina.com], User [userId=2, userName=tom, userPassword=123, userEmail=tom@sina.com], User [userId=3, userName=jack, userPassword=123, userEmail=jack@sina.com]]

备注

如果你利用IDEA创建的工程,在加载mapper.xml文件的时候,出现类似现象:

mybatis错误——java.io.IOException: Could not find resource com/xxx/xxxMapper.xml

那么,你可以在pom.xml文件的添加如下字段:

 <build>
        <!--idea不会寻找src/main/java目录下的xml配置-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

IDEA是不会编译src的java目录的xml文件,所以在Mybatis的配置文件中找不到xml文件!(也有可能是Maven构建项目的问题,网上教程很多项目是普通的Java web项目,所以可以放到src下面也能读取到)

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/195646.html

(0)
上一篇 2021年11月16日
下一篇 2021年11月16日

相关推荐

发表回复

登录后才能评论