赞
踩
上地址:https://github.com/C0de8ug/Javaee-tutorial
感谢C0de8ug上传的项目,帮助了许许多多像我们这样走在框架学习路上的新人们。
不多说,开始主题
代码:
import java.sql.Statement;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBAccess {
public static void main(String[] args) throws SQLException, FileNotFoundException, IOException
{
DBAccess access = new DBAccess();
access.test();
}
private void test() throws SQLException, FileNotFoundException, IOException
{
String url = "jdbc:postgresql://localhost:5432/rylynn";
Properties p = new Properties();
p.load(new FileInputStream("reg.txt"));
Connection connection = DriverManager.getConnection(url,p); //建立connection
Statement statement = connection.createStatement(); //建立satatement
statement.execute("insert into abo values((001),'hnb')"); //执行sql语句
ResultSet resultSet = statement.executeQuery("select number from abo where number < 2");
while(resultSet.next())
{
int id = resultSet.getInt(1);
// String name = resultSet.getString(1);
System.out.println("ID:" + id);
}
statement.close();
connection.close();
}
}
传统数据库访问模式缺点显而易见:
一就是各个模块间的耦合太紧,statement要依赖connection,connection还依赖于数据库的种类。
二就是如果我改变的数据库的种类,或者要提供不同的数据库服务,那么我就要提供大量的重复代码。
这里用C0de8ug公开在github上面的项目的代码来说明
dao层、service层以及service实现类的结构:
项目中使用了mybatis框架进行数据库的操作
以对于user的操作为例进行说明:
userdao:
public interface UserDao { public List<User> findAll(); public User findById(String id); public void update(User user); public void add(User user); public void delete(String id); public User findByIdAndPassword(@Param("id") String username, @Param("password") String password); public void updatePassword(@Param("userId") String id, @Param("password") String password); User findByUsername(String username);}
在接口中对方法进行了定义,在UserDao.xml中给出了sql语句实现
在UserDao中,就对user这个实体的增删补查各类基本的操作进行了声明,并用mybatis框架进行实现。
下面给出部分UserDao.xml的代码
<select id="findAll" resultMap="user_map">
SELECT * FROM user WHERE user_id != 'admin'
</select>
<select id="findById" parameterType="String" resultMap="user_map">
SELECT * FROM user WHERE user_id = #{value}
</select>
<update id="update" parameterType="User">
UPDATE user SET password = #{password} ,authority = #{authority} WHERE user_id = #{userId}
</update>
<update id="updatePassword" parameterType="map">
UPDATE user SET password = #{password} WHERE user_id = #{userId}
</update>
<insert id="add" parameterType="User">
INSERT INTO user(user_id,password,salt,role_ids,locked) VALUES(#{userId},#{password},#{salt},#{roleIdsStr},#{locked})
</insert>
<select id="findByIdAndPassword" parameterType="map" resultMap="user_map">
SELECT * FROM user WHERE user_id = #{id} AND password = #{password}
</select>
下面来看看service层的代码
import com.giit.www.entity.User;
import com.giit.www.entity.custom.UserVo;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Set;
/**
* Created by c0de8ug on 16-2-9.
*/
public interface UserBiz {
public List<UserVo> findAll() throws InvocationTargetException, IllegalAccessException;
public User findById(String id);
public void update(User user);
public void add(User user);
public void delete(String id);
public void changePassword(String userId, String newPassword);
public User findByUsername(String username);
public Set<String> findRoles(String username);
public Set<String> findPermissions(String username);
}
显然,service层里面的方法相较于dao层中的方法进行了一层包装,例如通过id查找用户,通过用户名查找用户,是在基础的操作上又增加了一层包装的,实现的是相对高级的操作。最后将这些操作在serviceimpl类中实现,代码比较多,这里还是只给出了部分代码,
import com.giit.www.college.dao.StaffDao;
import com.giit.www.entity.Role;
import com.giit.www.entity.Staff;
import com.giit.www.entity.User;
import com.giit.www.entity.custom.UserVo;
import com.giit.www.system.dao.RoleDao;
import com.giit.www.system.dao.UserDao;
import com.giit.www.system.service.RoleBiz;
import com.giit.www.system.service.UserBiz;
import com.giit.www.util.PasswordHelper;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* Created by c0de8ug on 16-2-9.
*/
@Service
public class UserBizImpl implements UserBiz {
@Resource
UserDao userDao;
@Resource
RoleDao roleDao;
@Resource
StaffDao staffDao;
@Resource
private PasswordHelper passwordHelper;
@Resource(name = "roleBizImpl")
private RoleBiz roleBiz;
@Override
public List<UserVo> findAll() throws InvocationTargetException, IllegalAccessException {
List<UserVo> userVoList = new ArrayList<>();
List userList = userDao.findAll();
Iterator iterator = userList.iterator();
while (iterator.hasNext()) {
StringBuilder s = new StringBuilder();
User user = (User) iterator.next();
List<Long> roleIds = user.getRoleIds();
UserVo userVo = new UserVo();
BeanUtils.copyProperties(userVo, user);
if (roleIds != null) {
int i = 0;
int size = roleIds.size();
for (; i < size - 1; i++) {
Role role = roleDao.findOne(roleIds.get(i));
s.append(role.getDescription());
s.append(",");
}
Role role = roleDao.findOne(roleIds.get(i));
s.append(role.getDescription());
userVo.setRoleIdsStr(s.toString());
}
userVoList.add(userVo);
}
return userVoList;
}
由此看到,这样进行分层,访问数据库和进行service之间的分工明确,如果我需要对service的需求修改,无需改变dao层的代码,只要在实现上改变即可,如果我有访问数据库的新需求,那我也只要在dao层的代码中增添即可。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。