发表于: 2019-12-26 19:45:27

2 1083


今天完成的事情:

1.添加数据返回ID

1)在UserMapper.xml中加入如下配置

<insert id="" parameterType="" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
useGeneratedKeys:必须设置为true,否则无法获取到主键id。
keyProperty:设置为POJO对象的主键id属性名称。
keyColumn:设置为数据库记录的主键id字段名称。 

2)在测试类中输出id

System.out.println("id:" + user.getId());


2.删除或更新数据返回True/False

1)修改service层的接口,删除更新的返回值是布尔类型

public boolean updateUser(User user) throws Exception;

public boolean deleteUser(int id) throws Exception;

2)修改它的实现类

@Override
public boolean updateUser(User user) throws Exception {
SqlSession sqlSession = this.getSqlSession();
   int update = sqlSession.update("test.updateUser", user);
   return update > 0;
}

@Override
public boolean deleteUser(int id) throws Exception {
SqlSession sqlSession = this.getSqlSession();
   int del = sqlSession.delete("test.deleteUser", id);
   return del > 0;
}

3)测试类

@Test
public void deleteUser() throws Exception {
// 通过配置资源对象获取 userService 对象
   UserService userService = (UserService) applicationContext.getBean("UserServiceImpl");
   boolean b = userService.deleteUser(13);
   if (b == true) {
System.out.println("删除成功!");
   } else {
System.out.println("删除失败!");
   }
}

@Test
public void updateUser() throws Exception {
// 通过配置资源对象获取 userService 对象
   UserService userService = (UserService) applicationContext.getBean("UserServiceImpl");
   User user = new User();
   user.setName("万万");
   user.setCreate_at(System.currentTimeMillis());
   user.setUpdate_at(System.currentTimeMillis());
   user.setQq(1197178284);
   user.setJob("java");
   user.setArrive_time(System.currentTimeMillis());
   user.setSchool("黑龙江科技大学");
   user.setStudent_id(121212);
   user.setLink("http://www.jnshu.com/school/39867/daily");
   user.setWish("加油!");
   user.setKnown_ways("朋友介绍");
   user.setBro("张恒");
   user.setId(3);
   boolean b = userService.updateUser(user);
   if (b == true) {
System.out.println("更新成功!");
   } else {
System.out.println("更新失败!");
   }
}


3.添加根据学员名字,学号去查找日报链接的单元测试

1)添加一个接口

public String selectUserByName(User user) throws Exception;

2)添加配置文件

<select id="selectUserByName" parameterType="com.wp.sm.beans.User" resultType="java.lang.String" >
   select link
   from student
where student_id = #{student_id} and name = #{name}
</select>

3)实现类

@Override
public String selectUserByName(User user) throws Exception {
SqlSession sqlSession = this.getSqlSession();
   String link=sqlSession.selectOne("test.selectUserByName",user);
   return link;
}

4)测试

@Test
public void selectUserByName() throws Exception {
// 通过配置资源对象获取 userService 对象
   UserService userService = (UserService) applicationContext.getBean("UserServiceImpl");
   // 调用 UserService 的方法
   User user = new User();
   user.setStudent_id(12);
   user.setName("九九");
   String link = userService.selectUserByName(user);
   // 输出报名贴地址
   System.out.println(link);
}


4.最终版代码

xml方式

1)实体类User

package com.wp.sm.beans;

public class User {

private long id;
   private String name;
   private long create_at;
   private long update_at;
   private int qq;
   private String job;
   private long arrive_time;
   private String school;
   private int student_id;
   private String link;
   private String wish;
   private String known_ways;
   private String bro;

   @Override
   public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", create_at=" + create_at +
", update_at=" + update_at +
", qq=" + qq +
", job='" + job + '\'' +
", arrive_time=" + arrive_time +
", school='" + school + '\'' +
", student_id=" + student_id +
", link='" + link + '\'' +
", wish='" + wish + '\'' +
", known_ways='" + known_ways + '\'' +
", bro='" + bro + '\'' +
'}';
   }

public long getId() {
return id;
   }

public void setId(long id) {
this.id = id;
   }

public String getName() {
return name;
   }

public void setName(String name) {
this.name = name;
   }

public long getCreate_at() {
return create_at;
   }

public void setCreate_at(long create_at) {
this.create_at = create_at;
   }

public long getUpdate_at() {
return update_at;
   }

public void setUpdate_at(long update_at) {
this.update_at = update_at;
   }

public int getQq() {
return qq;
   }

public void setQq(int qq) {
this.qq = qq;
   }

public String getJob() {
return job;
   }

public void setJob(String job) {
this.job = job;
   }

public long getArrive_time() {
return arrive_time;
   }

public void setArrive_time(long arrive_time) {
this.arrive_time = arrive_time;
   }

public String getSchool() {
return school;
   }

public void setSchool(String school) {
this.school = school;
   }

public int getStudent_id() {
return student_id;
   }

public void setStudent_id(int student_id) {
this.student_id = student_id;
   }

public String getLink() {
return link;
   }

public void setLink(String link) {
this.link = link;
   }

public String getWish() {
return wish;
   }

public void setWish(String wish) {
this.wish = wish;
   }

public String getKnown_ways() {
return known_ways;
   }

public void setKnown_ways(String known_ways) {
this.known_ways = known_ways;
   }

public String getBro() {
return bro;
   }

public void setBro(String bro) {
this.bro = bro;
   }

public User() {
}
}

2)Dao层接口UserMapper

package com.wp.sm.mapper;

import com.wp.sm.beans.User;

import java.util.List;

public interface UserMapper {

public int insertUser(User user) throws Exception;

   public boolean updateUser(User user) throws Exception;

   public boolean deleteUser(int id) throws Exception;

   public User selectUserById(int id) throws Exception;

   public List<User> selectAllUser() throws Exception;

   public String selectUserByName(User user) throws Exception;
}

3)Service层接口UserService

package com.wp.sm.service;

import com.wp.sm.beans.User;

import java.util.List;

public interface UserService {
public int insertUser(User user) throws Exception;

   public boolean updateUser(User user) throws Exception;

   public boolean deleteUser(int id) throws Exception;

   public User selectUserById(int id) throws Exception;

   public List<User> selectAllUser() throws Exception;

   public String selectUserByName(User user) throws Exception;
}

4)Service层实现类UserServiceImpl

package com.wp.sm.service.impl;

import com.wp.sm.beans.User;
import com.wp.sm.service.UserService;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserServiceImpl extends SqlSessionDaoSupport implements UserService {
@Override
   public int insertUser(User user) throws Exception {
SqlSession sqlSession = this.getSqlSession();
       int insert = sqlSession.insert("test.insertUser", user);
       return insert;
   }

@Override
   public boolean updateUser(User user) throws Exception {
SqlSession sqlSession = this.getSqlSession();
       int update = sqlSession.update("test.updateUser", user);
       return update > 0;
   }

@Override
   public boolean deleteUser(int id) throws Exception {
SqlSession sqlSession = this.getSqlSession();
       int del = sqlSession.delete("test.deleteUser", id);
       return del > 0;
   }

@Override
   public User selectUserById(int id) throws Exception {
SqlSession sqlSession = this.getSqlSession();
       User user = sqlSession.selectOne("test.selectUserById", id);
       return user;
   }

@Override
   public List<User> selectAllUser() throws Exception {
SqlSession sqlSession = this.getSqlSession();
       List<User> user = sqlSession.selectList("test.selectAllUser");
       return user;
   }

@Override
   public String selectUserByName(User user) throws Exception {
SqlSession sqlSession = this.getSqlSession();
       String link=sqlSession.selectOne("test.selectUserByName",user);
       return link;
   }
}

5)UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
   <insert id="insertUser" parameterType="com.wp.sm.beans.User" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
       insert into student (name, create_at, update_at, qq, job, arrive_time, school, student_id, link, wish,
known_ways, bro)
values (#{name}, #{create_at}, #{update_at}, #{qq}, #{job}, #{arrive_time}, #{school},
#{student_id}, #{link}, #{wish}, #{known_ways}, #{bro})
</insert>

   <update id="updateUser" parameterType="com.wp.sm.beans.User">
       update student
set name        = #{name},
create_at   = #{create_at},
update_at   = #{update_at},
qq          = #{qq},
job         = #{job},
arrive_time = #{arrive_time},
school      = #{school},
student_id  = #{student_id},
link        = #{link},
wish        = #{wish},
known_ways  = #{known_ways},
bro         = #{bro}
where id = #{id}
</update>

   <delete id="deleteUser" parameterType="int" >
       delete
from student
where id = #{id}
</delete>

   <select id="selectUserById" parameterType="int" resultType="com.wp.sm.beans.User">
       select *
       from student
where id = #{id}
</select>

   <select id="selectAllUser" parameterType="com.wp.sm.beans.User" resultType="com.wp.sm.beans.User">
       select *
       from student
</select>

   <select id="selectUserByName" parameterType="com.wp.sm.beans.User" resultType="java.lang.String" >
       select link
       from student
where student_id = #{student_id} and name = #{name}
</select>
</mapper>

6)测试类

import com.wp.sm.beans.User;
import com.wp.sm.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class UserServiceTest {
private ApplicationContext applicationContext;

   // 在执行测试方法之前首先获取 Spring 配置文件对象
   // 注解@Before在执行本类所有测试方法之前先调用这个方法
   @Before
   public void setup() throws Exception {
applicationContext = new
               ClassPathXmlApplicationContext("classpath:applicationContext.xml");
   }

@Test
   public void selectUserByName() throws Exception {
// 通过配置资源对象获取 userService 对象
       UserService userService = (UserService) applicationContext.getBean("UserServiceImpl");
       // 调用 UserService 的方法
       User user = new User();
       user.setStudent_id(12);
       user.setName("九九");
       String link = userService.selectUserByName(user);
       // 输出报名贴地址
       System.out.println(link);
   }

@Test
   public void selectUserById() throws Exception {
// 通过配置资源对象获取 userService 对象
       UserService userService = (UserService) applicationContext.getBean("UserServiceImpl");
       // 调用 UserService 的方法
       User user = userService.selectUserById(1);
       // 输出用户信息
       System.out.println(user.toString());
   }

@Test
   public void selectAllUser() throws Exception {
// 通过配置资源对象获取 userService 对象
       UserService userService = (UserService) applicationContext.getBean("UserServiceImpl");
       // 调用 UserService 的方法
       List<User> user = userService.selectAllUser();
       // 输出用户信息
       System.out.println(user.toString());
   }

@Test
   public void deleteUser() throws Exception {
// 通过配置资源对象获取 userService 对象
       UserService userService = (UserService) applicationContext.getBean("UserServiceImpl");
       boolean b = userService.deleteUser(13);
       if (b == true) {
System.out.println("删除成功!");
       } else {
System.out.println("删除失败!");
       }
}

@Test
   public void updateUser() throws Exception {
// 通过配置资源对象获取 userService 对象
       UserService userService = (UserService) applicationContext.getBean("UserServiceImpl");
       User user = new User();
       user.setName("万万");
       user.setCreate_at(System.currentTimeMillis());
       user.setUpdate_at(System.currentTimeMillis());
       user.setQq(1197178284);
       user.setJob("java");
       user.setArrive_time(System.currentTimeMillis());
       user.setSchool("黑龙江科技大学");
       user.setStudent_id(121212);
       user.setLink("http://www.jnshu.com/school/39867/daily");
       user.setWish("加油!");
       user.setKnown_ways("朋友介绍");
       user.setBro("张恒");
       user.setId(3);
       boolean b = userService.updateUser(user);
       if (b == true) {
System.out.println("更新成功!");
       } else {
System.out.println("更新失败!");
       }
}

@Test
   public void insertUser() throws Exception {
// 通过配置资源对象获取 userService 对象
       UserService userService = (UserService) applicationContext.getBean("UserServiceImpl");
       User user = new User();
       user.setName("peter");
       user.setCreate_at(System.currentTimeMillis());
       user.setUpdate_at(System.currentTimeMillis());
       user.setQq(1197178284);
       user.setJob("java");
       user.setArrive_time(System.currentTimeMillis());
       user.setSchool("黑龙江科技大学");
       user.setStudent_id(121212);
       user.setLink("http://www.jnshu.com/school/39867/daily");
       user.setWish("加油!");
       user.setKnown_ways("朋友介绍");
       user.setBro("张恒");
       userService.insertUser(user);
       System.out.println("id:" + user.getId());
   }
}

7)Spring的配置文件

<?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: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/context https://www.springframework.org/schema/context/spring-context.xsd">
   <!-- 加载配置文件 -->
   <context:property-placeholder location="classpath:db.properties"/>

   <!-- 配置数据源 -->
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="driverClass" value="${driver}"/>
       <property name="jdbcUrl" value="${url}"/>
       <property name="user" value="${username}"/>
       <property name="password" value="${password}"/>
   </bean>

   <!-- sqlSessionFactory -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <!-- 加载 MyBatis 的配置文件 -->
       <property name="configLocation" value="mybatis.xml"/>
       <!-- 数据源 -->
       <property name="dataSource" ref="dataSource"/>
   </bean>
   <bean id="UserServiceImpl" class="com.wp.sm.service.impl.UserServiceImpl">
       <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
   </bean>
</beans>

8)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>
   <!--mybatis.xml里注册UserMapper.xml文件-->
   <mappers>
       <mapper resource="com/wp/sm/mapper/UserMapper.xml"/>
   </mappers>
</configuration>

9)log4j.properties

# Global logging configuration
# 在开发环境下日志级别要设置成 DEBUG ,生产环境设为 INFO 或 ERROR
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

10)db.properties

username=root
password=19980710
url=jdbc:mysql://localhost:3306/sign_up?characterEncoding=UTF-8
driver=com.mysql.cj.jdbc.Driver


注解方式

主要是Spring配置文件和测试类略有不同

1)Spring配置文件

<?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: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/context https://www.springframework.org/schema/context/spring-context.xsd">
   <!-- 加载配置文件 -->
   <context:property-placeholder location="classpath:db.properties"/>
   <context:component-scan base-package="com.wp.sm"></context:component-scan>

   <!-- 配置数据源 -->
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="driverClass" value="${driver}"/>
       <property name="jdbcUrl" value="${url}"/>
       <property name="user" value="${username}"/>
       <property name="password" value="${password}"/>
   </bean>

   <!-- sqlSessionFactory -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <!-- 加载 MyBatis 的配置文件 -->
       <property name="configLocation" value="mybatis.xml"/>
       <!-- 数据源 -->
       <property name="dataSource" ref="dataSource"/>
   </bean>
   <bean id="UserServiceImpl" class="com.wp.sm.service.impl.UserServiceImpl">
       <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
   </bean>
</beans>

2)测试类

import com.wp.sm.beans.User;
import com.wp.sm.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserServiceTest {

@Autowired
   UserService us;

   @Test
   public void selectUserByName() throws Exception {
User user = new User();
       user.setStudent_id(12);
       user.setName("九九");
       String link = us.selectUserByName(user);
       // 输出报名贴地址
       System.out.println(link);
   }

@Test
   public void selectUserById() throws Exception {
User user = us.selectUserById(1);
       // 输出用户信息
       System.out.println(user.toString());
   }

@Test
   public void selectAllUser() throws Exception {
List<User> user = us.selectAllUser();
       // 输出用户信息
       System.out.println(user.toString());
   }

@Test
   public void deleteUser() throws Exception {
boolean b = us.deleteUser(11);
       if (b == true) {
System.out.println("删除成功!");
       } else {
System.out.println("删除失败!");
       }
}

@Test
   public void updateUser() throws Exception {
User user = new User();
       user.setName("万万");
       user.setCreate_at(System.currentTimeMillis());
       user.setUpdate_at(System.currentTimeMillis());
       user.setQq(1197178284);
       user.setJob("java");
       user.setArrive_time(System.currentTimeMillis());
       user.setSchool("黑龙江科技大学");
       user.setStudent_id(121212);
       user.setLink("http://www.jnshu.com/school/39867/daily");
       user.setWish("加油!");
       user.setKnown_ways("朋友介绍");
       user.setBro("张恒");
       user.setId(3);
       boolean b = us.updateUser(user);
       if (b == true) {
System.out.println("更新成功!");
       } else {
System.out.println("更新失败!");
       }
}

@Test
   public void insertUser() throws Exception {
User user = new User();
       user.setName("peter");
       user.setCreate_at(System.currentTimeMillis());
       user.setUpdate_at(System.currentTimeMillis());
       user.setQq(1197178284);
       user.setJob("java");
       user.setArrive_time(System.currentTimeMillis());
       user.setSchool("黑龙江科技大学");
       user.setStudent_id(121212);
       user.setLink("http://www.jnshu.com/school/39867/daily");
       user.setWish("加油!");
       user.setKnown_ways("朋友介绍");
       user.setBro("张恒");
       us.insertUser(user);
       System.out.println("id:" + user.getId());
   }
}


明天计划的事情:

学习深度思考的全部内容。


遇到的问题:

1.实现学员名字,学号去查找日报链接的功能的时候遇到了一些问题。

1)xml文件中,之前写的返回值是User类型,师兄提醒我返回值应该是String类型,因为只需要返回链接。

resultType="java.lang.String"

忘记加java.lang了,直接写的String

2)大括号里student_id我写成了id导致运行的时候本来是int型数据结果变成long型了

where student_id = #{student_id} and name = #{name}

3)最主要的问题是实现类中忘记传参了

String link=sqlSession.selectOne("test.selectUserByName");

正确写法:

String link=sqlSession.selectOne("test.selectUserByName",user);

都改正过了之后就跑通了,自己水平还是不行的啊。

2.在修改用注解方法实现增删改查的代码中,发现运行的时候报空指针异常。

师兄帮我加了这个代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")

运行时又报了错,原因是在Spring的配置文件中已经定义了一个bean,在实现类中又自动注入了一个bean

所以把实现类中的@Service注解去掉之后就跑通了。

收获:

从各种各样的bug中积累了不少知识,这就是收获吧。


返回列表 返回列表
评论

    分享到