【=。=】个人觉得MyBatis的注解实现其实并没有xml好用和方便,首先它违背了MyBatis的代码和数据库分离的设计原则,另外复杂的sql查询通过注解的方式实现并不如在xml里面配置看起来直观明了,方便修改。如果项目比较简单,涉及到的sql语句也比较简单,通过注解实现MyBatis或许是不错的选择呢。
1.搭载了WindowsOs的pc一台
2.确保jdk1.7可正常运行
3.确保mysql可正常运行
4.确保eclipse可正常运行
5.jar包准备(可前往阿里云资源库下载相关jar包点击打开链接)
1.新建项目(file ==》new ==》Dynamic web project)
2.把下载好的jar包放入,复制粘贴即可
3.全选==》右键==》build path ==》all
4.添加单元测试所需的jar包
项目名==》右键==》build path ==》config...
5.项目目录预览
#创建用户表
create table user(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
sex varchar(10),
address varchar(20)
);
1.mybatis.cfg.xml(src包下直接创建)
1.User.java(创建与数据库相对应的实体类)
package com.jiuwea.model;
public class User {
/**id*/
private Integer id;
/**用户名*/
private String username;
/**密码*/
private String password;
/**性别*/
private String sex;
/**地址*/
private String address;
public Integer getId() {
return id;
}
public void setId(Integer 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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", sex=" + sex + ", address="
+ address + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
2.UserMapper.java(创建映射接口)
package com.jiuwea.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.jiuwea.model.User;
public interface UserMapper {
/**
* 新增用户
* @param user
* @return
* @throws Exception
*/
@Insert("insert into user(username,password,sex,address) values (#{username},#{password},#{sex},#{address})")
@Options(useGeneratedKeys = true,keyProperty = "id")
public int insertUser(User user) throws Exception;
/**
* 修改用户
* @param user
* @return
* @throws Exception
*/
@Update("update user set password=#{password} where id=#{id}")
public int updateUser(User user) throws Exception;
/**
* 删除用户
* @param id
* @return
* @throws Exception
*/
@Delete("delete from user where id = #{id}")
public int deleteUser(Integer id) throws Exception;
/**
* 根据用户id查询用户信息
* @return
* @throws Exception
*/
@Select("select * from user where id = #{id}")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "sex",column = "sex"),
@Result(property = "address",column = "address")
})
public User selectUserById(Integer id) throws Exception;
/**
* 查询出全部用户的信息
* @return
* @throws Exception
*/
@Select("select * from user")
public List selectAllUser() throws Exception;
}
3.编写测试类
package com.jiuwea.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding.Use;
import javax.websocket.Session;
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.jiuwea.mapper.UserMapper;
import com.jiuwea.model.User;
public class Test {
private static SqlSessionFactory sqlSessionFactory;
static {
//获取mybatis 的配置文件
String resource = "mybatis.cfg.xml";
//创建配置文件流
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
//创建会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
/**
* 新增用户
*/
public static void insertUser(){
SqlSession sqlSession = sqlSessionFactory.openSession(); //会话工厂打开会话
UserMapper mapper = sqlSession.getMapper(UserMapper.class); //结果集
User user = new User();
user.setUsername("jiuwea");
user.setSex("女");
user.setPassword("jiuwea");
user.setAddress("上海市浦东新区北蔡镇北艾路");
try {
mapper.insertUser(user); //执行插入操作
sqlSession.commit(); //提交
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback(); //若有异常事务回滚
} finally {
sqlSession.close(); //最后关闭session
}
}
/**
* 更新用户
*/
public static void updateUser(Integer id) {
//打开会话
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = null;
try {
user = mapper.selectUserById(id);
} catch (Exception e) {
e.printStackTrace();
}
user.setPassword("123456");
try {
int result = mapper.updateUser(user);
if(result == 1) {
System.out.println("更新成功!");
}else {
System.out.println("更新失败!");
}
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}finally {
session.close();
}
}
/**
* 根据id删除用户
*/
public static void deleteUser(Integer id) {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
try {
int result = mapper.deleteUser(id);
if(result == 1) {
System.out.println("删除成功!");
}else {
System.out.println("删除失败!");
}
session.commit();//事务提交
} catch (Exception e) {
e.printStackTrace();
session.rollback();//异常回滚
} finally {
session.close();
}
}
/**
* 查找出来所有的用户
*/
public static void selectAllUser() {
//创建会话
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
try {
List users = mapper.selectAllUser();
System.out.println("查找出来的用户为:");
for (User user : users) {
System.out.println(user.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
/**
* 根据id查找用户
*/
public static void selectUserById( Integer id) {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = null;
try {
user = mapper.selectUserById(id);
if(user != null) {
System.out.println("查找成功:"+user.toString());
}else {
System.out.println("查找失败:"+user);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 测试创建用户
*/
@org.junit.Test
public void insertUserTest() {
for(int i = 0;i<7;i++) {
insertUser();
}
}
/**
* 测试删除用户
*/
@org.junit.Test
public void deleteUserTest() {
//删除id为10的用户
deleteUser(10);
}
/**
* 根据id查找用户
*/
@org.junit.Test
public void selectUserByIdTest() {
selectUserById(7);
}
/**
* 查找出来所有的用户
*/
@org.junit.Test
public void selectAllUserTest() {
selectAllUser();
}
/**
* 更新用户信息测试
*/
@org.junit.Test
public void updateUserTest() {
updateUser(11);
}
}
1.全选带有 @org.junit.Test 注解的方法名 ==》右键==》run as ==》junit test
2.结果
SqlSessionFactoryBuildder 创建出 SqlSessionFactory
SqlSessionFactory 打开SqlSession
SqlSession来和数据库进行数据交互
commit();方法是开启事务
rollback();事务回滚
close();关闭会话避免造成不必要的空间浪费
【ಥ﹏ಥ】