java web开发(mybatis编程)

Posted 嵌入式-老费

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java web开发(mybatis编程)相关的知识,希望对你有一定的参考价值。

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】

        目前java web标准的开发模式是ssm,前面两个s就是我们熟悉的spring和spring mvc。至于m,就是今天要聊的mybatis。使用mybatis,既需要使用配置文件mybatis-config.xml,也需要把sql语句写到***Dao.xml文件中。这就是它和hibernate不一样的地方。

        本文主要参考了两个链接,分别是链接1https://blog.csdn.net/aaa958099161/article/details/108098946,链接2https://juejin.cn/post/7042311420561588260,在此一并表示感谢。

        下面,就可以描述一下应该如何配置和使用mybatis。

1、利用IDEA+maven创建一个maven-archetype-quickstart工程

2、工程命名为Hello,不停单击Next,直到工程创建结束

3、修改pom.xml文件

3.1 添加依赖

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>


    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>

 3.2 在build下的pluginManagement后面添加资源说明

    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>

      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>

4、创建数据库java_web,并且创建一个user.sql导入表,表的内容如下所示,


CREATE TABLE `user` (
 
  `id` int(11) NOT NULL AUTO_INCREMENT,
 
  `name` varchar(50) NOT NULL,
 
  `birthday` datetime DEFAULT NULL,
 
  `sex` varchar(1) DEFAULT NULL,
 
  `address` varchar(50) DEFAULT NULL,
 
  PRIMARY KEY (`id`)
 
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

5、添加User.java类

package org.example;

import java.io.Serializable;
import java.util.Date;


public class User implements Serializable 
    private Integer id;
    private String name;
    private Date birthday;
    private String sex;
    private String address;


    @Override

    public String toString() 

        return "User" +

                "id=" + id +

                ", name='" + name + '\\'' +

                ", birthday=" + birthday +

                ", sex='" + sex + '\\'' +

                ", address='" + address + '\\'' +

                '';

    

    public Integer getId() 

        return id;

    

    public void setId(Integer id) 

        this.id = id;

    


    public String getName() 

        return name;

    

    public void setName(String name) 

        this.name = name;

    

    public Date getBirthday() 

        return birthday;

    

    public void setBirthday(Date birthday) 

        this.birthday = birthday;

    

    public String getSex() 

        return sex;

    


    public void setSex(String sex) 

        this.sex = sex;

    

    public String getAddress() 

        return address;

    

    public void setAddress(String address) 

        this.address = address;

    

6、添加IUserDao.java类

package org.example;

import java.util.List;

public interface IUserDao 
    List<User> findAll();

7、添加IUserDao.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="org.example.IUserDao">
    <select id="findAll" resultType="org.example.User">
        select * from user
        </select>
</mapper>

        注意,这个文件在mybatis-config.xml中会被引用到。

8、修改App.java文件

package org.example;

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.IOException;
import java.io.InputStream;
import java.util.List;


/**
 * Hello world!
 *
 */
public class App 

    public static void main( String[] args )
    
        /* define local variable*/
        InputStream in =null;
        SqlSession sqlSession=null;

        /* read xml file and make initial configuration */
        try 
            in = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSession = new SqlSessionFactoryBuilder().build(in).openSession();
        catch(IOException ioe)
            return;
        

        /* get user data from sqlSession */
        IUserDao iUserDao = sqlSession.getMapper(IUserDao.class);
        List<User> list =iUserDao.findAll();
        for (User user:list)
            System.out.println(user);
        

        /* database reading finished, close everything peacefully */
        try 
            in.close();
        catch(IOException ioe) 
            System.out.println("exception happened in in.close()");
        
        finally 
            sqlSession.close();
        
    

9、在src/main下面创建resources目录,创建mybatis-config.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="mysql">
        <environment id="mysql">
            <!--事务类型  -->
            <transactionManager type="JDBC"/>

            <!--连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/java_web"/>
                <property name="username" value="root"/>
                <property name="password" value="19850721"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 映射指定文件-->
    <mappers>
        <mapper resource="org/example/IUserDao.xml"/>
    </mappers>
</configuration>

10、所有配置文件文件都准备好后,结构如下所示,

11、利用maven-》“Hello”-》“Lifecycle”-》“compile”进行编译

12、到了这一步,就可以开始运行App.class文件了,

       执行过程中,如果有弹窗,选择“Hello”即可,

       不出意外的话,就可以看到这样的打印信息,

"C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\bin\\java.exe" "-javaagent:C:\\Program Files\\JetBrains\\IntelliJ IDEA 2020.1.1\\lib\\idea_rt.jar=59510:C:\\Program Files\\JetBrains\\IntelliJ IDEA 2020.1.1\\bin" -Dfile.encoding=UTF-8 -classpath "C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\charsets.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\deploy.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\access-bridge-32.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\cldrdata.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\dnsns.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\jaccess.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\jfxrt.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\localedata.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\nashorn.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\sunec.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\sunjce_provider.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\sunmscapi.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\sunpkcs11.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\ext\\zipfs.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\javaws.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\jce.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\jfr.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\jfxswt.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\jsse.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\management-agent.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\plugin.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\resources.jar;C:\\Program Files (x86)\\Java\\jdk1.8.0_91\\jre\\lib\\rt.jar;C:\\Users\\feixiaoxing\\Desktop\\Hello\\target\\classes;D:\\software\\apache-maven-3.6.3-bin\\repository\\org\\mybatis\\mybatis\\3.4.5\\mybatis-3.4.5.jar;D:\\software\\apache-maven-3.6.3-bin\\repository\\mysql\\mysql-connector-java\\5.1.47\\mysql-connector-java-5.1.47.jar" org.example.App
Sat Oct 08 06:52:56 CST 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Userid=1, name='tom', birthday=Sat Oct 08 06:13:03 CST 2022, sex='m', address='china'

Process finished with exit code 0

        注意,数据是自己在数据库里面添加的,显示的内容由自己来设定的。

以上是关于java web开发(mybatis编程)的主要内容,如果未能解决你的问题,请参考以下文章

java web开发(mybatis编程)

了解MyBatis——让开发更简捷与规范

eclipse下配置安装ssm图文教程(web版)

阿里巴巴Java开发手册1.7.0(嵩山版)编程规约&MySQL 数据库规约

Java版分布式微服务云开发架构 Spring Cloud+Spring Boot+Mybatis

Java之MyBatisIDEA版(一篇文章精通系列)增删改查XML开发 - 所有知识点(大全)