1. Table (mysql is used here, the database name is yiibai)
CREATE TABLE `user` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(64) NOT NULL DEFAULT '',
`dept` varchar(254) NOT NULL DEFAULT '',
`website` varchar(254) DEFAULT '',
`phone` varchar(16) NOT NULL DEFAULT '',
`birthday` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`);
2. The corresponding entity class User.java (pojo) of the table and the mybatis table map configuration file User.xml
package com.yiibai.mybatis.models;
import java.util.Date;
public class User {
public User(int id, String name, String dept, String phone, String website, Date birthday) {
super();
this.id = id;
this.name = name;
this.dept = dept;
this.phone = phone;
this.website = website;
this.birthday = birthday;
}
public User() {
super();
// TODO 自动生成的构造函数存根
}
private int id;
private String name;
private String dept;
private String phone;
private String website;
private Date birthday;
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", dept=" + dept + ", phone=" + phone + ", website=" + website
+ ", birthday=" + birthday + "]";
}
}
The configuration file User.xml is placed under the package com.yiibai.mybatis.models like the User class. The GetUserByID method is configured here for the purpose of mixing explanation and annotation methods. The actual application may be more powerful in XML configuration, but the annotation method is more intuitive and convenient. understand.
<?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.yiibai.mybatis.models.UserMapper">
<select id="GetUserByID" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>
</mapper>
3. Dao interface
package com.yiibai.mybatis.dao;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.yiibai.mybatis.models.User;
public interface IUser {
@Select("select * from user where id= #{id}")
public User getUserByID(int id);
@Insert("insert into user(id, name, dept,phone,website,birthday) values(#{id}, #{name}, #{dept},#{phone}, #{website}, #{birthday})")
public int insertUser(User user);
@Delete("delete from user where id=#{id}")
public int deleteUserById(int id);
@Update("update user set name=#{name},dept=#{dept},phone=#{phone},website=#{website},birthday=#{birthday} where id=#{id}")
public int updateUser(User user);
@Select("select * from user")
public List<User> getAllUser();
public User oneByID(int id);
}
The only method oneByID that is not annotated here is implemented in XML
Fourth, the Dao implementation class UserDaoImpl inherits SqlSessionDaoSupport and implements the IUser interface just now
package com.yiibai.mybatis.daoimpl;
import java.util.List;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.yiibai.mybatis.dao.IUser;
import com.yiibai.mybatis.models.User;
public class UserDaoImpl extends SqlSessionDaoSupport implements IUser {
@Override
public User getUserByID(int id) {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(IUser.class).getUserByID(id);
}
@Override
public int insertUser(User user) {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(IUser.class).insertUser(user);
}
@Override
public int deleteUserById(int id) {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(IUser.class).deleteUserById(id);
}
@Override
public int updateUser(User user) {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(IUser.class).updateUser(user);
}
@Override
public List<User> getAllUser() {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(IUser.class).getAllUser();
}
@Override
public User oneByID(int id) {
// TODO 自动生成的方法存根
return this.getSqlSession().selectOne("com.yiibai.mybatis.models.UserMapper.GetUserByID", id);
}
}
It can be seen here that the oneByID method is accomplished by calling the GetUserByID method under the User.xml namespace com.yiibai.mybatis.models.UserMapper.
5. Configuration file
The mybatis configuration file cfg.xml and the spring bean configuration file Userbean.xml are placed under com.yiibai.mybatis:
<?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>
<typeAliases>
<typeAlias alias="User" type="com.yiibai.mybatis.models.User" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/yiibai?useSSL=false" />
<property name="username" value="y-user" />
<property name="password" value="y-passwd" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- XML的方式 注册映射配置文件-->
<mapper resource="com/yiibai/mybatis/models/User.xml" />
<!--接口的方式 注册接口-->
<mapper class="com.yiibai.mybatis.dao.IUser"/>
</mappers>
</configuration>
It can be seen that both XML and interface methods are loaded in mapper.
You can also call this.sqlSessionFactory.getConfiguration().addMapper(IUser.class) in the main class to register
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool
http://www.springframework.org/schema/tool/spring-tool.xsd">
<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/yiibai?useSSL=false" />
<property name="username" value="your-name" />
<property name="password" value="your-passwd" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource1" />
<property name="configLocation"
value="classpath:com/yiibai/mybatis/cfg.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>
<bean id="MybatisUserDao" class="com.yiibai.mybatis.daoimpl.UserDaoImpl">
<property name="sqlSessionTemplate" ref="sqlSession" />
</bean>
</beans>
6. Main category
package com.yiibai.mybatis;
import java.sql.Date;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiibai.mybatis.dao.IUser;
import com.yiibai.mybatis.models.User;
public class UserBeanTest {
private static ApplicationContext ctx;
public static void main(String[] args) throws Exception {
ctx = new ClassPathXmlApplicationContext("com/yiibai/mybatis/Userbean.xml");
IUser iuser = (IUser) ctx.getBean("MybatisUserDao");
User user = new User(2, "yiibai2", "Tech", "13800009900", "http://www.zjptcc.com", Date.valueOf("1977-08-09"));
iuser.insertUser(user);
System.out.println(iuser.getUserByID(2));
System.out.println(iuser.oneByID(2));
List<User> users = iuser.getAllUser();
for (User u : users) {
System.out.println("user ID " + u.getId());
System.out.println("名字: " + u.getName());
System.out.println("所属部门" + u.getDept());
System.out.println("电话" + u.getPhone());
System.out.println("网址" + u.getWebsite());
System.out.println("日期" + u.getBirthday());
System.out.println("----------------------------");
}
iuser.deleteUserById(2);
}
}
7. The sping bean does not have to be configured (Userbean.xml is not configured), you can declare a SqlSessionFactory variable in the main class, then the main class can look like this:
package com.yiibai.mybatis;
import java.io.Reader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
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 com.yiibai.mybatis.dao.IUser;
import com.yiibai.mybatis.models.*;
/**
*
* @author yiibai
* @copyright http://www.yiibai.com
* @date 2015/09/22
*/
public class TestUser {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("com/yiibai/mybatis/cfg.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
SqlSession session = sqlSessionFactory.openSession();
try {
User user = (User) session.selectOne(
"com.yiibai.mybatis.models.UserMapper.GetUserByID", 1);
System.out.println(user);
IUser userInterface = session.getMapper(IUser.class);
user = (User) userInterface.getUserByID(1);
System.out.println(user);
userInterface.insertUser(new User(2,"依依2","Tech","13800009922","http://www.zjptcc.com", new SimpleDateFormat("yyyy-MM-dd").parse("1973-11-05"))) ;
List<User> users = userInterface.getAllUser();
for (User u : users) {
System.out.println("user ID " + u.getId());
System.out.println("名字: " + u.getName());
System.out.println("所属部门" + u.getDept());
System.out.println("电话" + u.getPhone());
System.out.println("网址" + u.getWebsite());
System.out.println("日期" + u.getBirthday());
System.out.println("----------------------------");
}
userInterface.deleteUserById(2);
session.commit();
} finally {
session.close();
}
}
}