hiberbae和mybatis中 和 的区别的区别

margin-left:10margin-top:5padding-left:10">
Archive for the ‘Getting started with MyBatis’ Category
This is a failry simple example using MyBatis Annotations. Good one to start with to get an overall view of how MyBatis makes things simplier, easier and faster.
Please notice the main method in UserBO class. All you need to do to test this example is, just run that class.
1. database.properties
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/database_name
database.username= ************
database.password= ************
2. configuration.xml
&configuration&
&properties resource="database.properties"/&
&environments default="development"&
&environment id="development"&
&transactionManager type="JDBC"/&
&dataSource type="POOLED"&
&property name="driver" value="${database.driver}"/&
&property name="url" value="${database.url}"/&
&property name="username" value="${database.username}"/&
&property name="password" value="${database.password}"/&
&/dataSource&
&/environment&
&/environments&
&mapper resource="com/mybatis/demo/user/UserMapper.xml"/&
&/mappers&
&/configuration&
3. 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.mybatis.demo.user.dao.UserDAO"&&/mapper&
4. ConnectionFactory Class
package com.mybatis.
import java.io.R
import org.apache.ibatis.io.R
import org.apache.ibatis.session.SqlSessionF
import org.apache.ibatis.session.SqlSessionFactoryB
public class ConnectionFactory {
private static SqlSessionFactory sqlM
private static R
= Resources.getResourceAsReader("configuration.xml");
sqlMapper = new SqlSessionFactoryBuilder().build(reader);
}catch(Exception e){
e.printStackTrace();
public static SqlSessionFactory getSession(){
return sqlM
5. UserVO Class
package com.mybatis.demo.user.
import java.io.S
import com.mybatis.demo.base.vo.BaseVO;
public class UserVO implements Serializable, BaseVO {
private static final long serialVersionUID = 0241018L;
private String fullN
public long getId(){
return this.
public void setId(long id) {
* @return the fullName
public String getFullName() {
return fullN
* @param fullName the fullName to set
public void setFullName(String fullName) {
this.fullName = fullN
* @return the address
public String getAddress() {
* @param address the address to set
public void setAddress(String address) {
this.address =
* @return the email
public String getEmail() {
* @param email the email to set
public void setEmail(String email) {
this.email =
* @return the mobile
public String getMobile() {
* @param mobile the mobile to set
public void setMobile(String mobile) {
this.mobile =
/* (non-Javadoc)
* @see java.lang.Object#toString()
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UserVO [address=");
builder.append(address);
builder.append(", email=");
builder.append(email);
builder.append(", fullName=");
builder.append(fullName);
builder.append(", id=");
builder.append(id);
builder.append(", mobile=");
builder.append(mobile);
builder.append("]");
return builder.toString();
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((fullName == null) ? 0 : fullName.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
public boolean equals(Object obj) {
if (this == obj)
if (obj == null)
if (getClass() != obj.getClass())
UserVO other = (UserVO)
if (fullName == null) {
if (other.fullName != null)
} else if (!fullName.equals(other.fullName))
if (id != other.id)
6. UserDAO Interface
package com.mybatis.demo.user.
import java.util.L
import org.apache.ibatis.annotations.D
import org.apache.ibatis.annotations.I
import org.apache.ibatis.annotations.S
import org.apache.ibatis.annotations.U
import com.mybatis.demo.user.vo.UserVO;
public interface UserDAO {
String MQL_GET_ALL_USERS
= "select * from users";
String MQL_GET_USER_BY_ID = "select * from users where id = #{id}";
String MQL_CREATE_USER
= "insert into users (fullName, email, address, mobile) values (#{fullName},#{email},#{address},#{mobile})";
String MQL_UPDATE_USER
= "update users set fullName=#{fullName}, email=#{email}, address=#{address}, mobile=#{mobile} where id=#{id}";
String MQL_DELETE_USER
= "delete from users where id=#{id}";
@Select(MQL_GET_ALL_USERS)
public List getAllUsers() throws E
@Select(MQL_GET_USER_BY_ID)
public UserVO getUserById(long id) throws E
@Insert(MQL_CREATE_USER)
public int doCreateUser(UserVO vo) throws E
@Update(MQL_UPDATE_USER)
public int doUpdateUser(UserVO vo) throws E
@Delete(MQL_DELETE_USER)
public int doDeleteUser(UserVO vo) throws E
7. UserBO Class
package com.mybatis.demo.user.
import java.util.L
import org.apache.ibatis.session.SqlS
import com.mybatis.demo.ConnectionF
import com.mybatis.demo.user.dao.UserDAO;
import com.mybatis.demo.user.vo.UserVO;
public class UserBO {
public List getUsers() throws Exception{
SqlSession session = ConnectionFactory.getSession().openSession();
UserDAO dao =session.getMapper(UserDAO.class);
List users= dao.getAllUsers();
session.close();
public UserVO getUserById(long id) throws Exception{
SqlSession session = ConnectionFactory.getSession().openSession();
UserDAO dao =session.getMapper(UserDAO.class);
UserVO user =dao.getUserById(id);
session.close();
public UserVO createUser(UserVO vo) throws Exception{
SqlSession session = ConnectionFactory.getSession().openSession();
UserDAO dao =session.getMapper(UserDAO.class);
dao.doCreateUser(vo);
session.close();
public UserVO updateUser(UserVO vo) throws Exception{
SqlSession session = ConnectionFactory.getSession().openSession();
UserDAO dao =session.getMapper(UserDAO.class);
dao.doUpdateUser(vo);
session.close();
public int deleteUser(UserVO vo) throws Exception{
SqlSession session = ConnectionFactory.getSession().openSession();
UserDAO dao =session.getMapper(UserDAO.class);
int cnt= dao.doDeleteUser(vo);
session.close();
public static void main(String a[])throws Exception{
UserBO bo = new UserBO();
UserVO vo= new UserVO();
vo.setAddress("Test");
vo.setEmail("");
vo.setFullName("Full Name");
vo.setMobile("");
System.out.println(bo.createUser(vo));
System.out.println(bo.getUsers());
vo= bo.getUserById(1);
vo.setAddress("Test Updated11 Address");
vo.setEmail("");
vo.setFullName("Full Name Test");
vo.setMobile("");
bo.updateUser(vo);
vo=bo.getUserById(1);
System.out.println(vo);
bo.deleteUser(vo);
Did you like this? Share it:
1. Download MyBatis3.0.2
I am using MyBatis3.0.2 to demonstrate all example in this blog.
Extract the zip file and place mybatis-3.0.2.jar under libraries (or) in your class path
2. Create a demo database. We explore MyBatis examples using this database.
You can find mybatis demo database scripts here:
Copy and execute the sql scripts and get your demo database ready to start experimenting mybatis.
3. database.properties file contents
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/database_name
database.username= ************
database.password= ************
4. configuration.xml file contents
&configuration&
&properties resource="database.properties"/&
&environments default="development"&
&environment id="development"&
&transactionManager type="JDBC"/&
&dataSource type="POOLED"&
&property name="driver" value="${database.driver}"/&
&property name="url" value="${database.url}"/&
&property name="username" value="${database.username}"/&
&property name="password" value="${database.password}"/&
&/dataSource&
&/environment&
&/environments&
&mapper resource="com/mybatis/demo/user/UserMapper.xml"/&
&/mappers&
&/configuration&
Take a look at my project explorer, this explains where I placed configuration files
(Well, its up to you on how you organize your code
MyBatisDemoProject Configuration
5. Obtaining MyBatis Session
import org.apache.ibatis.io.R
import org.apache.ibatis.session.SqlSessionF
import org.apache.ibatis.session.SqlSessionFactoryB
public class ConnectionFactory {
private static SqlSessionFactory sqlM
private static R
= Resources.getResourceAsReader("configuration.xml");
sqlMapper = new SqlSessionFactoryBuilder().build(reader);
}catch(Exception e){
e.printStackTrace();
public static SqlSessionFactory getSession(){
return sqlM
Did you like this? Share it:
Dear Readers,
All examples in this blog will be based on the schema below. I’ve chosen MySQL to demonstrate MyBatis examples, as it is fun, fast, lightweight, easy to setup and use.
MyBatis Demo Database Schema
Please find below sql script. Copy and paste to get going
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_
CREATE SCHEMA IF NOT EXISTS `mybatis_demodb` DEFAULT CHARACTER SET latin1 ;
USE `mydb` ;
USE `mybatis_demodb` ;
-- -----------------------------------------------------
-- Table `mybatis_demodb`.`users`
-- -----------------------------------------------------
TABLE IF NOT EXISTS `mybatis_demodb`.`users` (
`id` INT(8) NOT NULL AUTO_INCREMENT ,
`fullname` VARCHAR(50) NOT NULL ,
`address` VARCHAR(100) NULL DEFAULT NULL ,
`email` VARCHAR(60) NULL DEFAULT NULL ,
`mobile` VARCHAR(15) NULL DEFAULT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `mybatis_demodb`.`address`
-- -----------------------------------------------------
TABLE IF NOT EXISTS `mybatis_demodb`.`address` (
`id` INT(11) NOT NULL AUTO_INCREMENT ,
`userid` INT(11) NOT NULL ,
`street` VARCHAR(50) NULL DEFAULT NULL ,
`city` VARCHAR(50) NULL DEFAULT NULL ,
`county` VARCHAR(50) NULL DEFAULT NULL ,
`postcode` INT(50) NULL DEFAULT NULL ,
`users_id` INT(8) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_user_address` (`userid` ASC) ,
INDEX `fk_address_users1` (`users_id` ASC) ,
CONSTRAINT `fk_address_users1`
FOREIGN KEY (`users_id` )
REFERENCES `mybatis_demodb`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `mybatis_demodb`.`modules`
-- -----------------------------------------------------
TABLE IF NOT EXISTS `mybatis_demodb`.`modules` (
`id` INT(11) NOT NULL AUTO_INCREMENT ,
`modulename` VARCHAR(50) NOT NULL ,
`moduledescription` VARCHAR(100) NULL DEFAULT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `mybatis_demodb`.`roles`
-- -----------------------------------------------------
TABLE IF NOT EXISTS `mybatis_demodb`.`roles` (
`id` INT(11) NOT NULL AUTO_INCREMENT ,
`rolename` VARCHAR(50) NOT NULL ,
`roledescription` VARCHAR(100) NULL DEFAULT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `mybatis_demodb`.`role_module`
-- -----------------------------------------------------
TABLE IF NOT EXISTS `mybatis_demodb`.`role_module` (
`id` INT(11) NOT NULL ,
`roleid` INT(11) NOT NULL ,
`moduleid` INT(11) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_module` (`moduleid` ASC) ,
INDEX `fk_role` (`roleid` ASC) ,
CONSTRAINT `fk_role`
FOREIGN KEY (`roleid` )
REFERENCES `mybatis_demodb`.`roles` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_module`
FOREIGN KEY (`moduleid` )
REFERENCES `mybatis_demodb`.`modules` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `mybatis_demodb`.`user_role`
-- -----------------------------------------------------
TABLE IF NOT EXISTS `mybatis_demodb`.`user_role` (
`id` INT(11) NOT NULL ,
`userid` INT(11) NOT NULL ,
`roleid` INT(11) NOT NULL ,
`users_id` INT(8) NOT NULL ,
`roles_id` INT(11) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_user_role_users1` (`users_id` ASC) ,
INDEX `fk_user_role_roles1` (`roles_id` ASC) ,
CONSTRAINT `fk_user_role_users1`
FOREIGN KEY (`users_id` )
REFERENCES `mybatis_demodb`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_user_role_roles1`
FOREIGN KEY (`roles_id` )
REFERENCES `mybatis_demodb`.`roles` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
Did you like this? Share it:
Search MyBatis Examples
Categories
891011121314
15161718192021
22232425262728}

我要回帖

更多关于 mybatis 和 的区别 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信