**
SSM框架:利用测试类实现增删改查(eclipse版本)
**
Eclipse版本
之前在网上学习的时候看到了许多的SSM框架的文章(因为刚刚接触这个框架,所以弄了很久),我写了一个测试增删改查的demo
下面是目录结构(还在自学当中,这个文件配置并不完善,希望对你有帮助)
我的目录结构中没有写service层,直接用dao层实现(着实不完整,慢慢加油)
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ybzy?serverTimezone=GMT%2B8
jdbc.user=root
jdbc.pass=123456
mybatis-config.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>
<properties resource="jdbc.properties"/>
<typeAliases>
<typeAlias alias="User" type="bean.User"/>
</typeAliases>
<environments default="develop">
<environment id="develop">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 分别配置数据库连接的驱动,url,用户名,密码 -->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.pass}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="dao/UserMapper.xml"/>
</mappers>
</configuration>
MyBatisUtil.java
package utils;
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;
public class MyBatisUtil {
public MyBatisUtil(){
}
private static final String RESOURCE = "mybatis-config.xml";
private static SqlSessionFactory sqlSessionFactory = null;
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
static {
Reader reader = null;
try {
reader = Resources.getResourceAsReader(RESOURCE);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
sqlSessionFactory = builder.build(reader,"develop");
} catch (Exception e1) {
e1.printStackTrace();
throw new ExceptionInInitializerError("初始化MyBatis错误,请检查配置文件或数据库");
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
public static SqlSession getSession(){
//sessionTL的get()方法根据当前线程返回其对应的线程内部变量
//也就是我们需要的Session,多线程情况下共享数据库链接是不安全的
//ThreadLocal保证了每个线程都有自己的Session�?
SqlSession session = threadLocal.get();
// 如果session为null,则打开�?个新的session
if (session == null){
session = (sqlSessionFactory !=null) ?sqlSessionFactory.openSession():null;
threadLocal.set(session); // 5
}
return session;
}
public static void closeSession(){
SqlSession session = (SqlSession) threadLocal.get(); // 2
threadLocal.set(null);
if (session !=null){
session.close();
threadLocal.remove();
}
}
}
实体类User.java
package bean;
public class User {
private int id;
private String username;
private String password;
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
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 User(){
super();
}
public User(String username,String password){
super();
this.username = username;
this.password = password;
}
public String toString(){
return "ID号: " +id +" , 用户名:" + username + ", 密码: "+ password;
}
}
接口IUserDao.java
package dao;
import java.util.List;
import bean.User;
public interface IUserDao {
public User findUserById(int id);
public List<User> findAll();
public int insertUsers(User user);
public int deleteUsers(int id);
public int updateUsers(User user);
}
实现类 UserDaoImpl.java
package dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import bean.User;
import utils.MyBatisUtil;
public class UserDaoImpl implements IUserDao{
@Override
public User findUserById(int id) {
SqlSession session = null;
User user = new User();
try {
session = MyBatisUtil.getSession();
user = session.selectOne("usersMapper.findUserById",id);
} catch (Exception e) {
e.printStackTrace();
}finally {
session.close();
}
return user;
}
public List<User> findAll() {
SqlSession session=null;
List<User> user=new ArrayList<User>();
session = MyBatisUtil.getSession();
user=session.selectList("usersMapper.findAll");
return user;
}
@Override
public int insertUsers(User user) {
// TODO Auto-generated method stub
SqlSession session = null;
int count = 0;
try {
session = MyBatisUtil.getSession();
String statement = "usersMapper.insertUsers";
count = session.insert(statement,user);
session.commit();
}catch(Exception e) {
e.printStackTrace();
}finally {
session.close();
}
return count;
}
//删除用户
@Override
public int deleteUsers(int id) {
// TODO Auto-generated method stub
SqlSession session=null;
int count=0;
try {
session = MyBatisUtil.getSession();
String statment = "usersMapper.deleteUsers";
count=session.delete(statment, id);
session.commit();
}catch(Exception e){
e.printStackTrace();
}finally {
session.close();
}
return count;
}
@Override
public int updateUsers(User user){
SqlSession session = null;
int count=0;
try {
session = MyBatisUtil.getSession();
String statement = "usersMapper.updateUsers";
count = session.update(statement, user);
session.commit();
}catch(Exception e){
e.printStackTrace();
}finally {
session.close();
}
return count;
}
}
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="usersMapper">
<!-- 配置结果映射 -->
<resultMap type="User" id="User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
</resultMap>
<select id="findUserById" parameterType="int" resultMap="User">
select * from student where id=#{id}
</select>
<select id="findAll" parameterType="User" resultMap="User">
select * from student
</select>
<insert id="insertUsers" parameterType="bean.User" useGeneratedKeys="true" keyProperty="id">
insert into student(username,password) values(#{username},#{password})
</insert>
<delete id="deleteUsers" parameterType="int">
delete from student where id = #{id}
</delete>
<update id="updateUsers" parameterType="bean.User">
update student set username=#{username},password=#{password} where id=#{id}
</update>
</mapper>
最后用于运行的关键一步
测试类:Test.java
package test;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import bean.User;
import dao.IUserDao;
import dao.UserDaoImpl;
public class Test {
public static void main(String[] args) throws IOException,SQLException {
updateUser();
}
public static void findByID() throws IOException,SQLException{
IUserDao userDao = new UserDaoImpl();
User user = userDao.findUserById(3);
System.out.println(user);
}
public static void findAll() {
IUserDao userDao = new UserDaoImpl();
List<User> user = userDao.findAll();
System.out.println(user);
}
public static void insertUser() throws IOException,SQLException{
IUserDao userDao = new UserDaoImpl();
User user = new User("Mr.K","123456");
userDao.insertUsers(user);
System.out.println("添加成功!");
}
public static void deleteUser() throws IOException,SQLException{
IUserDao userDao = new UserDaoImpl();
int count=userDao.deleteUsers(2);
if(count>0) System.out.println("成功删除!");
}
public static void updateUser() throws IOException,SQLException{
IUserDao userDao=new UserDaoImpl();
User user = new User();
user.setId(3);
user.setUsername("Mr.Shen");
user.setPassword("XXXXXX");
int count = userDao.updateUsers(user);
if(count>0) System.out.println("修改成功");
System.out.println("修改了"+count+"行");
}
}
MySQL数据库
有什么问题,欢迎大家在下面评论,望各位大佬指点