Spring Mybatis实例SqlSessionDaoSupport混用xml配置和注解


声明:本文转载自https://my.oschina.net/u/2245781/blog/1554379,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

一、表(这里用mysql,数据库名为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`);

二、表相应的实体类User.java以及mybatis表map配置文件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 + "]"; 	}  } 

配置文件User.xml和User类一样放在包com.yiibai.mybatis.models下,这里只是为了解释和注解方法混用就配置了 GetUserByID一个方法,实际应用可能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.yiibai.mybatis.models.UserMapper"> 	<select id="GetUserByID" parameterType="int" resultType="User"> 		select * from `user` where id = #{id}     </select> </mapper>

三、Dao接口

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(#{name}, #{id}, #{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);  } 

这里唯一没有用注解的方法oneByID用XML方式来实现

四、Dao实现类UserDaoImpl继承SqlSessionDaoSupport并实现了刚才的IUser接口

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); 	}  } 

这里可以看出oneByID方法是通过调用User.xml名字空间com.yiibai.mybatis.models.UserMapper下面GetUserByID的方法来完成的。

四、配置文件

mybatis配置文件cfg.xml和spring bean的配置文件都放在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>

可以看出mapper中把XML和接口方式都加载了。

也可以在主类中调用this.sqlSessionFactory.getConfiguration().addMapper(IUser.class)来注册

<?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>

五、主类

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);  	}  } 

 

本文发表于2017年10月22日 08:34
(c)注:本文转载自https://my.oschina.net/u/2245781/blog/1554379,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 1690 讨论 0 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1