04 编写service层,利用自动生成的mapper接口,mapper.xml操作数据库
之前的一系列操作,得到了我们操作数据库的接口,我们下面来使用这些接口,对数据库操作
项目目录如下,service层如下:
(1)编写UserLoginService接口
我们实现了两个方法,用户登陆和注册
package com.example.demo.service;
public interface UserLoginService {
String login(String account,String password);
String register(String account,String password);
}
(2)编写UserLoginImpl
这个类,继承上述的UserLoginService,并且声明了@service注解,故后面编写的controller会扫描到
package com.example.demo.service.impl;
import com.example.demo.entity.UserLogin;
import com.example.demo.mapper.UserLoginMapper;
import com.example.demo.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserLoginImpl implements UserLoginService {
@Autowired
UserLoginMapper userLoginMapper;
@Override
public String login(String account,String password) {
try{
UserLogin user=userLoginMapper.selectByPrimaryKey(account);
if(user.getUserAccount().equals(account)&&user.getUserPassword().equals(password))
{
return "success";
}
else {
return "failure";
}
}
catch(NullPointerException e){
//e.printStackTrace();
//System.out.println("size = 0");
return "failure";
}
}
@Override
public String register(String account, String password) {
UserLogin userLogin=new UserLogin();
userLogin.setUserAccount(account);
userLogin.setUserPassword(password);
try{
int value=userLoginMapper.insert(userLogin);
if(value>0)
{
return "success";
}
else {
return "failure";
}
}
catch(Exception e){
//e.printStackTrace();
//System.out.println("size = 0");
return "failure";
}
}
}