1. 新建一个名为SpringMybatis的Java项目, 添加相关jar包。
2. 在src目录下配置jdbc.properties
3. 在src目录下配置SqlMapConfig.xml
4. 在src目录下配置applicationContext.xml
5. 创建User.java
package com.lywgames.domain;
import java.util.Date;
public class User {
private Integer id;
private String name;
private String sex;
private Date birthday;
private String address;
public User() {
}
public User(String name, String sex, Date birthday, String address) {
this.name = name;
this.sex = sex;
this.birthday = birthday;
this.address = address;
}
public User(Integer id, String name, String sex, Date birthday, String address) {
this.id = id;
this.name = name;
this.sex = sex;
this.birthday = birthday;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address
+ "]";
}
}
6. 创建UserMapper.java
package com.lywgames.dao;
import java.util.List;
import com.lywgames.domain.User;
public interface UserMapper {
public List<User> selectUser();
}
7. 在和UserMapper.java相同的包下, 创建UserMapper.xml
8. 创建UserService.java
package com.lywgames.service;
import java.util.List;
import com.lywgames.domain.User;
public interface UserService {
List<User> selectUser();
}
9. 创建UserServiceImpl.java
package com.lywgames.service.impl;
import java.util.List;
import com.lywgames.dao.UserMapper;
import com.lywgames.domain.User;
import com.lywgames.service.UserService;
public class UserServiceImpl implements UserService {
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public List<User> selectUser() {
return userMapper.selectUser();
}
}
10. 创建Test.java
package com.lywgames;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lywgames.domain.User;
import com.lywgames.service.UserService;
public class Test {
public static void main(String[] args) {
// 类路径加载配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取UserService
UserService userService = context.getBean(UserService.class);
// 查询操作
List<User> users = userService.selectUser();
for (User user : users) {
System.out.println(user);
}
}
}
11. 数据库user表内容
12. 运行结果