翻着看了好多有关Spring的IOC DI的资料终于搞懂了一点点,再加上之前学的MyBatis,综合使用了一下。
commons-logging-1.2.jar
log4j-1.2.17.jar
mybatis-3.4.4.jar
mysql-connector-java-5.1.42-bin.jar
spring-beans-4.3.9.RELEASE.jar
spring-context-4.3.9.RELEASE.jar
spring-core-4.3.9.RELEASE.jar
spring-expression-4.3.9.RELEASE.jar
以上几个jar请自行百度下载
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`mail` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', 'mrdong916', '123', '[email protected]');
INSERT INTO `users` VALUES ('2', 'ceshi2', '2133', '[email protected]');
INSERT INTO `users` VALUES ('3', 'ceshi3', '2133', '[email protected]');
INSERT INTO `users` VALUES ('4', 'ceshi4', '34324', '[email protected]');
INSERT INTO `users` VALUES ('5', 'ceshi5', '3fgtr4', '[email protected]');
配置mybatis全局配置
<configuration>
<properties resource="jdbc.properties">properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper class="com.dyh.mapping.UserMapperInterface"/>
<mapper resource="com/dyh/mapping/UserMapperXml.xml" />
mappers>
configuration>
配置JDBC
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis
username=root
password=123456
配置log4j
log4j.rootLogger =ALL,systemOut
log4j.appender.systemOut = org.apache.log4j.ConsoleAppender
log4j.appender.systemOut.layout = org.apache.log4j.PatternLayout
log4j.appender.systemOut.layout.ConversionPattern = [%-5p][%-22d{yyyy/MM/dd HH\:mm\:ssS}][%l]%n%m%n
log4j.appender.systemOut.Threshold = WARN
log4j.appender.systemOut.ImmediateFlush = TRUE
log4j.appender.systemOut.Target = System.out
创建实体类
package com.dyh.model;
public class User {
private int userId;
private String userName;
private String password;
private String mail;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
@Override
public String toString() {
return "User信息: [userId=" + userId + ", userName=" + userName
+ ", password=" + password + ", mail=" + mail + "]";
}
public void init() {
// TODO Auto-generated method stub
System.err.println("Init.............");
}
public void destory() {
// TODO Auto-generated method stub
System.err.println("Destory.............");
}
}
配置Bean
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="User" class="com.dyh.model.User" init-method="init" destroy-method="destory" >bean>
beans>
创建service接口
package com.dyh.service;
import java.util.List;
import com.dyh.model.User;
public interface UserContrallerInterface {
public List selectAllUser();
public List selectUserByuserName(String userName);
public User selectUserById(int userId);
public void updateUser(User user);
public void deleteUserByuserName(String userName);
public void deleteUserById(int userId);
public void addUser(User user);
}
两种方式实现对数据库的操作
创建UserMapperByInterface.java
package com.dyh.mapping;
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.dyh.model.User;
public interface UserMapperInterface {
@Insert("insert into users (userName,password,mail) values(#{userName},#{password},#{mail})")
public void addUser(User user);
@Delete("delete from users where id=#{userId}")
public void deleteUserById(int userId);
@Delete("delete from users where userName=#{userName}")
public void deleteUserByuserName(String userName);
@Update("update users set userName=#{userName},password=#{password},mail=#{mail} where id=#{userId}")
public void updateUser(User user);
@Select("select id,userName,password,mail from users where id=#{userId}")
public User selectUserById(int userId);
@Select("select id,userName,password,mail from users where userName=#{userName}")
public List selectUserByuserName(String userName);
@Select("select id,userName,password,mail from users order BY id ASC")
public List selectAllUser();
}
实现对services接口对用户的增删改查
package com.dyh.dao;
import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.dyh.mapping.UserMapperInterface;
import com.dyh.model.User;
import com.dyh.service.UserContrallerInterface;
import com.dyh.utils.MyBatisUtil;
public class UserContrallerByInterface implements UserContrallerInterface{
static SqlSession session;
static{
try {
session = MyBatisUtil.getSqlSession(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(session == null){
session.close();
}
}
}
/**
* 增加用户
* @param user
*/
public void addUser(User user){
session.getMapper(UserMapperInterface.class).addUser(user);
}
/**
* 通过用户昵称删除用户
* @param userName
*/
public void deleteUserByuserName(String userName){
session.getMapper(UserMapperInterface.class).deleteUserByuserName(userName);
}
/**
* 通过用户ID删除用户
* @param userId
*/
public void deleteUserById(int userId){
session.getMapper(UserMapperInterface.class).deleteUserById(userId);
}
/**
* 修改用户信息
* @param userName
*/
public void updateUser(User user){
session.getMapper(UserMapperInterface.class).updateUser(user);
}
/**
* 通过用户Id查询用户
* @param userId
* @return
*/
public User selectUserById(int userId){
User resultUser = session.getMapper(UserMapperInterface.class).selectUserById(userId);
return resultUser;
}
/**
* 通过用户用户昵称查询用户
* @param userName
* @return
*/
public List selectUserByuserName(String userName){
List list= session.getMapper(UserMapperInterface.class).selectUserByuserName(userName);
return list;
}
/**
* 查询所有用户
* @return 所有用户
*/
public List selectAllUser(){
List list= session.getMapper(UserMapperInterface.class).selectAllUser();
return list;
}
}
通过XML文件实现数据库操作
创建UserMapperXml.xml文件
<mapper namespace="com.dyh.mapping.UserMapper" >
<insert id="addUser" parameterType="com.dyh.model.User">
insert into users (userName,password,mail)values(#{userName},#{password},#{mail});
insert>
<delete id="deleteUserById" parameterType="int">
delete from users where id=#{userId}
delete>
<delete id="deleteUserByuserName" parameterType="com.dyh.model.User">
delete from users where userName=#{userName}
delete>
<update id="updateUser" parameterType="com.dyh.model.User">
update users set userName=#{userName},password=#{password},mail=#{mail} where id=#{userId}
update>
<select id="selectUserById" parameterType="int" resultType="com.dyh.model.User">
select * from users where id=#{userId}
select>
<select id="selectUserByuserName" parameterType="String" resultType="com.dyh.model.User">
select * from users where userName=#{userName}
select>
<select id="selectAllUser" resultType="com.dyh.model.User">
select * from users order by id asc;
select>
mapper>
实现services接口对用户的增删改查
package com.dyh.dao;
import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.dyh.model.User;
import com.dyh.service.UserContrallerInterface;
import com.dyh.utils.MyBatisUtil;
public class UserContrallerByXml implements UserContrallerInterface{
static SqlSession session;
static{
try {
session = MyBatisUtil.getSqlSession(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(session == null){
session.close();
}
}
}
/**
* 增加用户
* @param user
*/
public void addUser(User user){
session.insert("com.dyh.mapping.UserMapper.addUser", user);
}
/**
* 通过用户昵称删除用户
* @param userName
*/
public void deleteUserByuserName(String userName){
session.delete("com.dyh.mapping.UserMapper.deleteUserByuserName", userName);
}
/**
* 通过用户ID删除用户
* @param userId
*/
public void deleteUserById(int userId){
session.delete("com.dyh.mapping.UserMapper.deleteUserById", userId);
}
/**
* 修改用户信息
* @param userName
*/
public void updateUser(User user){
session.update("com.dyh.mapping.UserMapper.updateUser", user);
}
/**
* 通过用户Id查询用户
* @param userId
* @return
*/
public User selectUserById(int userId){
User resultUser = session.selectOne("com.dyh.mapping.UserMapper.selectUserById", userId);
return resultUser;
}
/**
* 通过用户用户昵称查询用户
* @param userName
* @return
*/
public List selectUserByuserName(String userName){
List list = session.selectList("com.dyh.mapping.UserMapper.selectUserByuserName", userName);
return list;
}
/**
* 查询所有用户
* @return 所有用户
*/
public List selectAllUser(){
List list = session.selectList("com.dyh.mapping.UserMapper.selectAllUser");
return list;
}
}
获取SqlSession的工具类
package com.dyh.utils;
import java.io.IOException;
import java.io.Reader;
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.dyh.constant.constant;
public class MyBatisUtil {
/**
* 获取SqlSessionFactory
* @return SqlSessionFactory
* @throws IOException
*/
public static SqlSessionFactory getSqlSessionFactory() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
return factory;
}
/**
* 获取SqlSession
* @return SqlSession
* @throws IOException
*/
public static SqlSession getSqlSession() throws IOException {
return getSqlSessionFactory().openSession();
}
/**
* 获取SqlSession
* @param isAutoCommit
* true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
* false 不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
* @return SqlSession
* @throws IOException
*/
public static SqlSession getSqlSession(boolean isAutoCommit) throws IOException {
return getSqlSessionFactory().openSession(isAutoCommit);
}
}
package com.dyh.test;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dyh.dao.UserContrallerByInterface;
import com.dyh.dao.UserContrallerByXml;
import com.dyh.model.User;
import com.dyh.service.UserContrallerInterface;
public class TestUser {
@Test
public void testUser() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserContrallerInterface ucxml = new UserContrallerByXml();
UserContrallerInterface ucinter = new UserContrallerByInterface();
User user = (User)ctx.getBean("User");
user.setUserId(5);
user.setUserName("ceshi5");
user.setPassword("3fgtr4");
user.setMail("[email protected]");
ucinter.addUser(user);
System.err.println(ctx.getBean("User"));
user.destory();
Logger logger = Logger.getLogger(TestUser.class);
for (User user1: ucxml.selectAllUser()) {
logger.error(user1);
}
for (User user2 : ucinter.selectAllUser()) {
System.err.println(user2);
}
}
}
在学校机房里测试的没问题,不知道为什么导入自己的电脑就存在id一直为0的问题了,后来找到了原因,是由于数据的列名和User类中属性名不一致导致的
代码下载
demo.zip