ssm框架学习----数据库操作增删改查

项目结构 首先配置配置文件:jdbc.properties

driver=com.mysql.jdbc.Driver	/*加载驱动*/
url=jdbc:mysql://域名+端口/数据库名称   /*数据库的域名和数据库的名称*/
username=
password=
#定义初始连接数  
initialSize=0  
#定义最大连接数  
maxActive=20  
#定义最大空闲  
maxIdle=20  
#定义最小空闲  
minIdle=1  
#定义最长等待时间  
maxWait=60000

1.查询数据 1.1首先写mapper层,写出数据库的具体列 注释: namespace代表了继承的接口

<resultMap id="BaseResultMap" type="com.javen.model.Login" >
  <!-- 数据库和本地的字段的对应关系 id是方法的名字 type用来指定的 -->

column代表数据库中的字段 property代表本地字段的写法 jdbcType代表数据中字段的类型 添加查询的sql语句

<select id="selectAll" resultMap="BaseResultMap" >
    select 
    <include refid="Base_Column_List" />
    from login
  </select>

注释: id是方法的名字 resultMap是返回的类型 refid中的Base_Column_List是自己设置的列名,如下:

<sql id="Base_Column_List" >
   	id,loginNum,userName,password,phoneNumber,idcard,sex
  </sql>

1.2写DAO层 根据mapper中的sql语句的入参类型和名称

List<Login> selectAll();

1.3写service层(接口层) 将dao层的代码复制过来

List<Login> selectAll();

1.4写servicelmpl层 继承service层 返回查询到的数据

@Service
public class ILoginServiceImpl implements ILoginService{
	@Resource
	private LoginDao loginDao;
	
	public List<Login> selectAll() {
		// TODO Auto-generated method stub
		return this.loginDao.selectAll();
	}
}

注释: 在类上面需要添加@service 在类实体上需添加@Resource 返回查询到的数据

1.5写controller层

@Controller  //
@RequestMapping("/login") 
public class LoginController {  
	
	private static Logger log=LoggerFactory.getLogger(LoginController.class);
	
	@Resource  
	private ILoginService loginService;     
    
    // /user/test?id=1
    @RequestMapping(value="/test/{id}", method=RequestMethod.GET)  
    @ResponseBody	//传输回去的是字符串不是页面
    public String test(@PathVariable String id){
    	System.out.println(id+"++++++++");
    	List<Login> logins=loginService.selectAll();
    	for (Login login : logins) {
			System.out.println(login);
		}
        return "index"; 
    }
}

注释: 开头需要添加 @Controller // @RequestMapping("/login") 此处的login是页面的名字 在服务层实体前需要添加@Resource @RequestMapping(value="/test/{id}", method=RequestMethod.GET) value是页面的该方法的页面名称 此处/{id}可以使用/1的方式代替?id=的方式 @ResponseBody //传输回去的是字符串不是页面,添加这句话之后返回的就是一个字符串不是页面了。

List<Login> logins=loginService.selectAll();

这句话是调用sql方法查询数据。

经验分享 程序员 微信小程序 职场和发展