Spring Mybatis整合小例子

1、新建JavaProject工程 spring-mybatis、部署spring、新建包、添加properties属性文件。目录如下:

Spring Mybatis整合小例子_第1张图片

2、applicationConetxt.xml文件已经把mybatis-config.xml中的dataSource、mappers等配置整合成bean或peroperty

  

  
  
  
 
 
 
 
 
 
  
  
  
  
 
 
 
 
  
  
  
  
 
 
 
 
 	
 	 	
 
 
 
   
      
          
     
 
 

3、mapper文件

 package com.mapper;
import java.util.List;
import com.model.Student;

public interface StudentMapper {

	public List getAllStudent();
}




	


4、实体类Student

package com.model;

public class Student {
	private int sno;
	private String sname;
	private double score;
	
	public int getSno() {
		return sno;
	}
	public void setSno(int sno) {
		this.sno = sno;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	public Student(int sno, String sname, double score) {
		super();
		this.sno = sno;
		this.sname = sname;
		this.score = score;
	}
	public Student() {
		super();
	}
	@Override
	public String toString() {
		return "Student [sno=" + sno + ", sname=" + sname + ", score=" + score + "]";
	}
	
	
}

5、从配置文件中获得ApplicationContext上下文的工具类

package com.tool;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppContext {

	private static ApplicationContext appContext;
	
	static{
		appContext=new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	
	public static T getBean(Class t){
		return appContext.getBean(t);
	}
}

6、service业务包

package com.service;

import java.util.List;

import com.model.Student;

public interface InterStudentService {

	public List showStudentList();
}
package com.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.mapper.StudentMapper;
import com.model.Student;
import com.tool.AppContext;

@Service
public class StudentServiceImpl implements InterStudentService {

	@Resource
	private StudentMapper studentMapper;	

	@Override
	public List showStudentList() {
		
		//ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		studentMapper=AppContext.getBean(StudentMapper.class);
		
		return studentMapper.getAllStudent();
	}

}

7、测试类Test

package com.test;

import com.service.InterStudentService;
import com.service.StudentServiceImpl;
import com.tool.AppContext;

public class Test {

	public static void main(String[] args) {
		
		//InterStudentService stuService=new StudentServiceImpl();
		
		InterStudentService stuService=AppContext.getBean(StudentServiceImpl.class);
		
		System.out.println(stuService.showStudentList());
		
	}
	
}

8、结果

Spring Mybatis整合小例子_第2张图片

你可能感兴趣的:(Spring Mybatis整合小例子)