标签:
新建一个实体类User (@Component注解,将一个对象放入容器中。)
新建一个接口UserDaoIface
package com.zhaoming.dao.iface; import java.util.List; import com.zhaoming.entity.User; public interface UserDaoIface { public List<User> queryAll(); public User addUser(User user); }
新建一个实现类UserDaoImp
package com.zhaoming.dao.imp; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import javax.annotation.Resource; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.zhaoming.dao.iface.UserDaoIface; import com.zhaoming.entity.User; @Repository public class UserDaoImp implements UserDaoIface{ @Resource JdbcTemplate jdbcTemplate; /* @Override public List<User> queryAll() { String sql = "select * from users"; List<User> list = jdbcTemplate.query(sql, new RowMapper<User>() { //匿名内部类 public User mapRow(ResultSet rs, int arg1) throws SQLException { User user = new User(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)); return user; } }); */ //兰姆达表达式 @Override public List<User> queryAll() { String sql = "select * from users"; List<User> list = jdbcTemplate.query(sql, (RowMapper<User>) (rs,index)-> new User(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)) ); return list; } @Override public User addUser(User user) { String sql = "insert into users values(seq_uid.nextval,?,?,?)"; User user0 = jdbcTemplate.execute((ConnectionCallback<User>) (connection) ->{ PreparedStatement psmt = connection.prepareStatement(sql,new String[]{"id"}); psmt.setString(1,user.getName() ); psmt.setString(2, user.getPassword()); psmt.setString(3, user.getTelephone()); psmt.executeUpdate(); ResultSet rs = psmt.getGeneratedKeys(); if(rs.next()) { user.setId(rs.getInt(1)); } return user; }); return user0; } }
测试
package com.zhaoming.userdao; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.zhaoming.dao.imp.UserDaoImp; import com.zhaoming.entity.User; import spring.config.DataSourceConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {DataSourceConfig.class}) public class UserDaoTest { @Resource UserDaoImp userDao; public void testQuery(){ List<User> list = userDao.queryAll(); for (User user : list) { System.out.println(user.getName()); } } @Test public void testAdd(){ User user = new User(0, "admin", "123", "321"); User user0 = userDao.addUser(user); System.out.println(user0.getId()); } }
标签:
原文地址:http://www.cnblogs.com/zmlion1995/p/5800777.html