fzhiy

Running all the time.

MyBatis——入门示例

点击量:4

前言

此文章只是mybatis的一个入门实例,之前自己也写过一个完整【大致内容都涵盖】的后台(SSH),但是使用hibernate过程中由于数据库设计部分联系太多,而hibernate相对mybatis操作起来不灵活,所以想试试mybatis。 (个人想法,有高见的大佬可以留言指教,谢谢!)

项目目录结构

《MyBatis——入门示例》《MyBatis——入门示例》

分层结构解析:

controller层:控制层【此项目没有用到,后面SSM或SSH整合时用到】,写前端调用做交互的类

dao层:接口层, 写接口类

entity层:实体层, 写与数据库表对应的实体类

这是比较经典的三层结构。

具体细节之后的文章进一步分析。

StudentDao.java

package com.fzhiy.dao;

import com.fzhiy.entity.Student;

public interface StudentDao {
	
	public int insertStudent(Student student);
}

《MyBatis——入门示例》

StudentMapper.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.fzhiy.dao.StudentDao">
	<!-- parameterTpye对应typeAlias别名 -->
	<insert id="insertStudent" parameterType="Student">
		insert into t_student values(null,#{name},#{age})
	</insert>
</mapper>

《MyBatis——入门示例》

Student.java

package com.fzhiy.entity;

public class Student {
	
	private Integer id;//自动生成
	private String name;
	private Integer age;
	
	
	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 Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Student() {
		super();
	}

	public Student(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	
}

《MyBatis——入门示例》

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>
	<!-- 引入外部资源文件 -->
    <properties resource="jdbc.properties"/>
    <typeAliases> <!-- 别名 -->
    	<typeAlias alias="Student" type="com.fzhiy.entity.Student"/>
    </typeAliases>
    <!-- 设置驼峰匹配 -->
 <!--    <settings>
      <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings> -->
    <!-- 配置环境:可以配置多个环境,default:配置某一个环境的唯一标识,表示默认使用哪个环境 -->
      <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>
      </environments>
      <!-- 配置映射文件 -->
      <mappers>
        <mapper resource="com/fzhiy/dao/StudentMapper.xml"/>
      </mappers>
</configuration>

《MyBatis——入门示例》

StudentTest.java

package com.fzhiy.test;

import org.apache.ibatis.session.SqlSession;

import com.fzhiy.dao.StudentDao;
import com.fzhiy.entity.Student;
import com.fzhiy.util.SqlSessionFactoryUtil;

public class StudentTest {
	public static void main(String[] args) {
		///数据库连接
		SqlSession sqlSession=SqlSessionFactoryUtil.openSession();
		StudentDao studentDao=sqlSession.getMapper(StudentDao.class);
		Student student=new Student("李四",11);
		int result=studentDao.insertStudent(student);
		//事务提交
		sqlSession.commit();
		if(result>0) {
			System.out.println("添加学生成功!");
		}
	}
}

《MyBatis——入门示例》

SqlSessionFactoryUtil.java

package com.fzhiy.util;

import java.io.InputStream;

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 SqlSessionFactoryUtil {
	
	private static SqlSessionFactory sqlSessionFactory;
	
	/**
	 * 数据库连接
	 * @return
	 */
	public static SqlSession openSession() {
		return getSqlSessionFactory().openSession();
	}
	
	private static SqlSessionFactory getSqlSessionFactory() {
		if(sqlSessionFactory == null) {
			InputStream inputStream=null;
			String resource = "mybatis-config.xml";
			try {
				inputStream=Resources.getResourceAsStream(resource);
				//配置文件的输入流
				sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return sqlSessionFactory;
	}
	
}

《MyBatis——入门示例》

运行结果

DEBUG – Logging initialized using ‘class org.apache.ibatis.logging.slf4j.Slf4jImpl’ adapter.
DEBUG – PooledDataSource forcefully closed/removed all connections.
DEBUG – PooledDataSource forcefully closed/removed all connections.
DEBUG – PooledDataSource forcefully closed/removed all connections.
DEBUG – PooledDataSource forcefully closed/removed all connections.
DEBUG – Opening JDBC Connection
DEBUG – Created connection 2015444413.
DEBUG – Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@78213dbd]
DEBUG – ==>  Preparing: insert into t_student values(null,?,?)
DEBUG – ==> Parameters: 李四(String), 11(Integer)
DEBUG – <==    Updates: 1
DEBUG – Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@78213dbd]
添加学生成功!

其他问题

【Java】Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException

配置文件及jar包

链接: https://pan.baidu.com/s/1k3fYSdsdqAOHx9a_5ApQuQ 提取码: 7bmx

点赞

发表评论

电子邮件地址不会被公开。