继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Dao模式创建mybatis项目过程

甜瓜在奔跑
关注TA
已关注
手记 1
粉丝 0
获赞 2

Java EE框架

1、表现层 springMVC
2、粘合剂 spring(IOC/控制反转 AOP/面向切面编程 DI/依赖注入)
3、持久层 mybatis

Dao模式创建mybatis项目过程

1、下载jar包

mybatis jar包下载地址:
链接:https://pan.baidu.com/s/1xvZauxhkAPYxWvoJuxlLFg 
提取码:ia7w 
复制这段内容后打开百度网盘手机App,操作更方便哦
mybatis中文手册地址:
http://www.dba.cn/book/mybatis/MYBATISZhongWenShouCe/MYBATISXMLPeiZhi.html

2、导入所需要的jar包

http://img.mukewang.com/5cc4f9cc0001b34a02960139.jpg
commons-logging-1.2.jar 用于日志处理
log4j-1.2.17.jar 日志系统,负责日志输出
mybatis-3.5.0.jar mybatis核心jar包
mysql-connector-java-5.1.46.jar MySQL数据库驱动jar包
将jar包部署到项目中

http://img3.mukewang.com/5cc4f9dc00010b8f03060241.jpg
3、编写mybatis核心配置文件

创建mybatis核心配置文件mybatis-config.xml
创建Java属性配置文件jdbc.properties
创建日志属性配置文件log4j.properties
http://img2.mukewang.com/5cc4f9ee0001e4d902820176.jpg

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD config.3.0//EN" 
"mybatis-3-config.dtd" >

<configuration>
 <properties resource="jdbc.properties"></properties>
 <typeAliases>
  <package name="com.Model"/>
 </typeAliases>
 <environments default="development">
  <environment id="development">
   <transactionManager type="JDBC">
   </transactionManager>
   <dataSource type="POOLED">
    <property name="driver" value="${jdbc.DriverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
   </dataSource>
  </environment>
 </environments>
 <mappers>
  <package name="com.user"/>
 </mappers>
</configuration>

jdbc.properties

jdbc.DriverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf-8
jdbc.username=用户名
jdbc.password=密码

log4j.properties

log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

4、创建实体类

创建实体类并生成seter/geter方法重写toString方法。

User.java

package com.model;
public class User {
 private int userId;
 private String userName;
 private String userPass;
 private int userSex;
 private int userAge;
 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 getUserPass() {
  return userPass;
 }
 public void setUserPass(String userPass) {
  this.userPass = userPass;
 }
 public int getUserSex() {
  return userSex;
 }
 public void setUserSex(int userSex) {
  this.userSex = userSex;
 }
 public int getUserAge() {
  return userAge;
 }
 public void setUserAge(int userAge) {
  this.userAge = userAge;
 }
 @Override
 public String toString() {
  return "User [userId=" + userId + ", userName=" + userName + ", userPass=" + userPass + ", userSex=" + userSex
    + ", userAge=" + userAge + "]";
 }

}

5、创建Dao接口

UserDao.java

package com.dao;
import com.model.User; 
public interface UserDao {
 public User findUserById(int Id);
 //通过id查询用户信息
 public void addUser(User user);
 //向数据库中增加用户信息
 public void deleteUser(int Id);
//删除用户信息
public void updateUser(User user);
//修改用户信息
}
userService.java
package com.service;
import com.model.User;
public interface userService {
 public User findUserById(int Id);
 public void addUser(User user);
 public void deleteUser(int Id);
 
public void updateUser(User user);
}

6、创建 sql 映射文件

在dao包下创建sql映射文件 UserDao.xml。这里使用mapper动态代理所以映射文件必须和接口UserDao.java在同一个包下。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper.3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="com.mzdx.dao.UserDao">
     <select id="findUserById" parameterType="int" resultType="user">
  select * from userdb where userId=#{Id}
     </select>
     <insert id="addUser" parameterType="user">
  insert into userdb (userName,userPass,userSex,userAge)
  values (#{userName},#{userPass},#{userSex},#{userAge})
    </insert> 
    <delete id="deleteUser" parameterType="int">
  delete from userdb where userId=#{value}
    </delete> 
    <update id="updateUser" parameterType="user"> 
 update userdb set userName=#{userName},userPass=#{userPass},userSex=#{userSex},userAge=#{userAge} 
 where userId=#{userId}
 </update>
</mapper>

7、单例模式创建SqlSessionFactory工厂

MyBatisUtilsLazy.java

package com.utils;

import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtilsLazy {
 public static SqlSessionFactory factory=null;
 public static SqlSessionFactory getFactory() {
  if (factory==null) {
   InputStream in;
   try {
   synchronized(MyBatisUtilsLazy.class){
   if (factory==null) {
      in =Resources.getResourceAsStream("mybatis-config.xml");
      factory = new SqlSessionFactoryBuilder().build(in);
     } 
    }
   } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
  }
  return factory;
 }
}

8、编写实现类

UserServiceImpl.java

package com.service.impl;
import org.apache.ibatis.session.SqlSession;
import com.dao.UserDao;
import com.model.User;
import com.service.userService;
import com.utils.MyBatisUtilsLazy;

public class UserServiceImpl implements userService {
     SqlSession session = MyBatisUtilsLazy.getFactory().openSession();
 UserDao mapper = session.getMapper(UserDao.class);
 @Override
 public User findUserById(int Id) {
  // TODO Auto-generated method stub
  return mapper.findUserById(Id);
 }
 @Override
 public void addUser(User user) {
  // TODO Auto-generated method stub
  try {
   mapper.addUser(user);
   session.commit();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally {
   session.close();
  }
 }
 @Override
 public void deleteUser(int Id) {
  // TODO Auto-generated method stub
  try {
   mapper.deleteUser(Id);
   session.commit();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally {
   session.close();
  }
 }
 @Override
 public void updateUser(User user) {
  // TODO Auto-generated method stub
  try {
   mapper.updateUser(user);
   session.commit();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally {
   session.close();
  }
 }
}

9、编写测试类

TestAddUser.java

package com.test;
import org.junit.Test;
import com.model.User;
import com.service.impl.UserServiceImpl;

public class TestAddUser {
 @Test
 public void testAddUser() {
  UserServiceImpl userServiceImpl = new UserServiceImpl();
  User user = new User();
  String userName="aaa";
  String userPass="152425";
  int userSex=0;
  int userAge=28;
  user.setUserName(userName);
  user.setUserPass(userPass);
  user.setUserSex(userSex);
  user.setUserAge(userAge);
  userServiceImpl.addUser(user);
  System.out.println(user);
 }
}

TestDeleteUser.java

package com.test;
import org.junit.Test;
import com.service.impl.UserServiceImpl;
public class TestDeleteUser {
 @Test
 public void testdeleteUser() {
  UserServiceImpl userServiceImpl = new UserServiceImpl();
  int Id=16;
  userServiceImpl.deleteUser(Id);
 }
}

TestFindUserById.java

package com.test;
import org.junit.jupiter.api.Test;
import com.model.User;
import com.service.impl.UserServiceImpl;

public class TestFindUserById {
 @Test
 public void testFindUserById(){
  UserServiceImpl userServiceImpl = new UserServiceImpl();
  int Id=17;
  User user = userServiceImpl.findUserById(Id);
  System.out.println(user);
 }
}

TestUpdateUser.java

package com.test;
import org.junit.Test;
import com.model.User;
import com.service.impl.UserServiceImpl;

public class TestUpdateUser {
 @Test
 public void testupdateUser() {
  UserServiceImpl userServiceImpl = new UserServiceImpl();
  User user = new User();
  String userName="张三";
  String userPass="152425";
  int userSex=0;
  int userAge=25;
  user.setUserId(18);
  user.setUserName(userName);
  user.setUserPass(userPass);
  user.setUserSex(userSex);
  user.setUserAge(userAge);
  userServiceImpl.updateUser(user);
  System.out.println(user);
 }
}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP