1. 程式人生 > >Mybatis-03 第一個Mybatis 專案

Mybatis-03 第一個Mybatis 專案

搭建第一個Mybatis專案

建立DTO

package www.mybatis01.beans;
public class User {
	private Integer userId;
	private String userName;
	private int age;
	//快捷鍵Alt+Shift+S+C
	public User() {
		super();
	}
	//快捷鍵Alt+Shift+S+O
	public User(String userName, int age) {
		super();
		this.userName = userName;
		this.age = age;
	}
	
	//快捷鍵Alt+Shift+S+R	
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	//快捷鍵Alt+Shift+S+S
	@Override
	public String toString() {
		return "User [userId=" + userId + ", userName=" + userName + ", age=" + age + "]";
	}
	
}

建立DTO介面

package www.mybatis01.dao;

import www.mybatis01.beans.User;

public interface IUserDao {
	public void addUser(User user);
	public int queryUser(int userID);
}

建立DTO介面實現

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

import www.mybatis01.beans.User;
import www.mybatis01.dao.IUserDao;
import www.mybatis01.utils.mybatisdao.MybatisDao;

public class UserMyBatisDao implements IUserDao {

	@Override
	public void addUser(User user) {
		try {
			//1:載入配置檔案
			InputStream input= Resources.getResourceAsStream("mybatis.xml");
			//2:建立SqlSessionFactory物件
			SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(input);
			//3:建立SqlSession物件
			SqlSession sqlSession = sqlSessionFactory.openSession();
			//4:相關操作		
			sqlSession.insert("user.addUser", user);
			sqlSession.commit();
			sqlSession.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Test測試

package www.mybatis01.test;

import org.junit.Test;
import org.junit.Before;

import www.mybatis01.beans.User;
import www.mybatis01.dao.IUserDao;
import www.mybatis01.dao.impl.UserMyBatisDao;

public class UserTest {
	
	private IUserDao userDao;
	
	@Before
	public void Before() {
		userDao =new UserMyBatisDao();
	}
	@Test
	public void testAdd() {
		User user = new User("小四",18);
		userDao.addUser(user);
	}
}

MySQL資料庫檔案


CREATE DATABASE `mysql`;
USE `mysql`;
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `userId` bigint(5) NOT NULL,
  `userName` varchar(50) DEFAULT NULL,
  `age` tinyint(3) DEFAULT NULL,
  `createdBy` varchar(50) DEFAULT NULL,
  `createdDate` timestamp NULL DEFAULT NULL,
  `updatedBy` varchar(50) DEFAULT NULL,
  `updatedDate` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `tb_user`(`userId`,`userName`,`age`,`createdBy`,`createdDate`,`updatedBy`,`updatedDate`) values 
(1,'張三',20,NULL,NULL,NULL,NULL),
(2,'李四',23,NULL,NULL,NULL,NULL),
(3,'王五',26,NULL,NULL,NULL,NULL);

mapper.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="user">
	<insert id="addUser" parameterType="www.mybatis01.beans.User">
		insert into tb_user(userName,age)
		values(#{userName},#{age})
	</insert>
</mapper>

mybatis.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.cj.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://127.0.0.1:3306/mysql?serverTimezone=UTC" />
				<property name="username" value="****" />
				<property name="password" value="****" />
				
			</dataSource>
		</environment>
	</environments>	
	<!-- 註冊對映檔案 -->
	<mappers>
		<mapper resource="www/mybatis01/dao/mapper.xml" />
	</mappers>
</configuration>
配置檔案注意事項
property url 省略預設內容
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mysql"/>
如果資料庫 地址為127.0.0.1 埠號為3306, 可以省略 jdbc:mysql:///mysq
<property name="url" value="jdbc:mysql:///mysq"/>
environments default一定要和environment 某個的Id一致 否則會報錯
	<!-- 配置執行環境 -->
	<environments default="mysql">
		<environment id="mysql">
		</environment>
		<environment id="oracle">
		</environment>
		<environment id="DB2">
		</environment>
	</environments>	
</configuration>
報錯:org.apache.ibatis.exceptions.PersistenceException:
報錯:
org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
 
需要設定serverTimezone=UTC
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mysql" />
改為:
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mysql?serverTimezone=UTC" />