【入门】Spring-Boot项目配置Mysql数据库

前言

    前面参照SpringBoot官网,自动生成了简单项目点击打开链接

配置数据库和代码遇到的问题

    问题1:cannot load driver class :com.mysql.jdbc.Driver不能加载mysql

    原因:没有添加依赖

    解决:pom.xml添加依赖


    mysql
    mysql-connector-java

    问题2:Consider defining a bean of type 'com.xx.dao.XxDao' in your configuration.注入UserDao失败

    原因:UserDao没有添加注解

    解决:在接口UserDao外层加上注解:@Mapper

    问题3:controller中注入service失败

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.boot.service.DemoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    原因:application.java文件默认扫描相同包名下的service,dao。

    解决:application.java文件添加注解:@ComponentScan(basePackages = "com.xxx")

配置Mysql数据库

在pom.xml添加依赖


    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    1.2.0

    mysql
    mysql-connector-java

在application.properties添加

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/girls
spring.datasource.username=root
spring.datasource.password=chendashan
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

server.port=8080
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8


mybatis.configLocations= classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml

    建立库表省略,文章末尾附带

mapper文件

    操作数据库,靠它完成。





	
	
		
		
		
		
	
      
      

    综上得知,UserDao通过映射文件mapper,执行了sql语句,返回了实体类User

UserDao接口

@Mapper
public interface UserDao {
	/**
	 * 根据user_name查询数据库
	 * (映射执行mapper文件中的sql语句selectUserByUserName)
	 * @param userName 名字
	 * @return User
	 */
	public User selectUserByUserName(String userName);
}

User实体类

public class User {
	private String userName;
	private String userPassword;

	public String getUserName() {
		return userName;
	}

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

	public String getUserPassword() {
		return userPassword;
	}

	public void setPassword(String userPassword) {
		this.userPassword = userPassword;
	}

}

逻辑结构

逻辑层在controller里处理,已知,执行Userdao的接口方法,即可操作数据库。为了更好处理逻辑分层,加入Service层,调用UserDao。在Service实现层,注入UserDao即可调用其方法。

@Service
public class UserServiceImp implements UserService {

	@Autowired
	private UserDao userDao;//注入UserDao
	
	@Override
	public User selectUserByName(String userName) {
		return userDao.selectUserByUserName(userName);
	}

}
public interface UserService {
	/**
	 * 通过姓名查找User
	 * @param userName
	 * @return
	 */
	User selectUserByName(String useName);
}

controller

    最后,controller层对外提供接口,返回查询数据结果

@Controller
public class UserController {
	
	@Autowired	
	private UserService userService;//注入Service
	
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map login(@RequestParam(value = "userName", required = true) String userName,
    		@RequestParam(value = "userPassword", required = true) String userPassword) {
		Map result = new HashMap();
		User user = null;  
		String retCode = "";
        String retMsg = "";  
        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPassword)){  
        	retCode = "01";  
        	retMsg = "用户名和密码不能为空";  
        }else{  
            user = userService.selectUserByName(userName);  
            if(null == user){  
            	retCode = "01";  
            	retMsg = "用户不存在";  
            }else{  
                if(userPassword.equals(user.getUserPassword())){  
                	retCode = "00";  
                	retMsg = "登录成功";  
                }else{  
                	retCode = "01";  
                	retMsg = "密码有误";  
                }  
            }  
        }  
        result.put(SystemConst.retCode, retCode);  
        result.put(SystemConst.retMsg, retMsg);  
		return result;
	}

}

girls.sql文件

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `girls_info`
-- ----------------------------
DROP TABLE IF EXISTS `girls_info`;
CREATE TABLE `girls_info` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(30) NOT NULL,
  `user_password` varchar(10) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of girls_info
-- ----------------------------
INSERT INTO `girls_info` VALUES ('1', '张帆', '123456');
INSERT INTO `girls_info` VALUES ('2', '李北', '123456');
INSERT INTO `girls_info` VALUES ('3', '陈珊珊', '123456');
INSERT INTO `girls_info` VALUES ('4', '王国立', '123456');
INSERT INTO `girls_info` VALUES ('5', '张三', '123456');
INSERT INTO `girls_info` VALUES ('6', '李四', '123456');
INSERT INTO `girls_info` VALUES ('7', 'Biligle', '123456');

下载地址:https://download.csdn.net/download/qq_29266921/10457479


你可能感兴趣的:(【入门】Spring-Boot项目配置Mysql数据库)