3.手写LcMybatis(3),多条件查询和模糊查询

1.

package com.lc.lcMybatis;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lc.pojo.Category;
import com.lc.pojo.Student;

public class LcSqlSession {
	private String modelPackage;
	private Map<String,Map<String, String>> mapInfo;
	
	private Connection connection;
	
	public String getModelPackage() {
		return modelPackage;
	}

	public void setModelPackage(String modelPackage) {
		this.modelPackage = modelPackage;
	}

	public Map<String,Map<String, String>> getMapInfo() {
		return mapInfo;
	}

	public void setMapInfo(Map<String,Map<String, String>> mapInfo) {
		this.mapInfo = mapInfo;
	}

	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	private final List<String> columnNames = new ArrayList<String>();
	private final List<String> classNames = new ArrayList<String>();
	
	
	
	public <E> E selectOne(String string, int id) {
		E object = null;
		try {
			Statement statement = connection.createStatement();
			Map map =mapInfo.get(string);
			String sql=(String) map.get("sql");
			sql=sql.replace("#{id}", id+"");
			ResultSet rs = statement.executeQuery(sql);
			
			final ResultSetMetaData metaData = rs.getMetaData();
		    final int columnCount = metaData.getColumnCount();
		    for (int i = 1; i <= columnCount; i++) {
		        columnNames.add( metaData.getColumnName(i));
		        classNames.add(metaData.getColumnClassName(i));
		    }
		    String resultType=(String) map.get("resultType");
		    String modelClassName=modelPackage+"."+resultType;
            //构造器
            Constructor constructor= Class.forName(modelClassName).getConstructor();
            while (rs.next()) {
		    	object=(E) constructor.newInstance();
		    	Map propertyMap=new HashMap();
		    	for (int i = 0; i < columnCount; i++) {
		    		Object paramValue=new Object();		    				
		    		if(classNames.get(i).equals("java.lang.Integer")){
		    			paramValue=rs.getInt(i+1);
		    		}else if(classNames.get(i).equals("java.lang.String")){
		    			paramValue=rs.getString(i+1);
		    		}
		    		String paramName=rs.getMetaData().getColumnName(i+1);
		    		propertyMap.put(paramName, paramValue);
				}
		    	setValue(object,propertyMap);
        	}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
	
	
	public <E> List<E> selectList(String sqlstring, Map<String, Object> params) {
		List<E> list=new ArrayList<E>();
		try {
			Statement statement = connection.createStatement();
			// 准备sql语句,注意: 字符串要用单引号'
			Map map =mapInfo.get(sqlstring);
			String sql=(String) map.get("sql");
			
			for (Map.Entry<String, Object> entry : params.entrySet()) {
	            //Map.entry<Integer,String> 映射项(键-值对)  有几个方法:用上面的名字entry
	            //entry.getKey() ;entry.getValue(); entry.setValue();
	            //map.entrySet()  返回此映射中包含的映射关系的 Set视图。
	            //System.out.println("key= " + entry.getKey() + " and value= "+ entry.getValue());
	            sql=sql.replace("#{"+entry.getKey()+"}", "'"+entry.getValue()+"'");
	        }
			
			//sql=sql.replace("#{0}", "'"+param+"'");
			
			
			//System.out.println(sql);
			ResultSet rs = statement.executeQuery(sql);
			
			final ResultSetMetaData metaData = rs.getMetaData();
		    final int columnCount = metaData.getColumnCount();
		    for (int i = 1; i <= columnCount; i++) {
		        columnNames.add( metaData.getColumnName(i));
		        classNames.add(metaData.getColumnClassName(i));
		    }
		    String resultType=(String) map.get("resultType");
		    String modelClassName=modelPackage+"."+resultType;
            //构造器
            Constructor constructor= Class.forName(modelClassName).getConstructor();
            
		    while (rs.next()) {
		    	Object object=constructor.newInstance();
		    	Map propertyMap=new HashMap();
		    	for (int i = 0; i < columnCount; i++) {
		    		Object paramValue=new Object();		    				
		    		if(classNames.get(i).equals("java.lang.Integer")){
		    			paramValue=rs.getInt(i+1);
		    		}else if(classNames.get(i).equals("java.lang.String")){
		    			paramValue=rs.getString(i+1);
		    		}
		    		String paramName=rs.getMetaData().getColumnName(i+1);
		    		propertyMap.put(paramName, paramValue);
				}
		    	setValue(object,propertyMap);
		    	list.add((E) object);
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	

	public <E> List<E> selectList(String sqlstring, String param) {
		List<E> list=new ArrayList<E>();
		try {
			Statement statement = connection.createStatement();
			// 准备sql语句,注意: 字符串要用单引号'
			Map map =mapInfo.get(sqlstring);
			String sql=(String) map.get("sql");
			
			sql=sql.replace("#{0}", "'"+param+"'");
			//System.out.println(sql);
			ResultSet rs = statement.executeQuery(sql);
			
			final ResultSetMetaData metaData = rs.getMetaData();
		    final int columnCount = metaData.getColumnCount();
		    for (int i = 1; i <= columnCount; i++) {
		        columnNames.add( metaData.getColumnName(i));
		        classNames.add(metaData.getColumnClassName(i));
		    }
		    String resultType=(String) map.get("resultType");
		    String modelClassName=modelPackage+"."+resultType;
            //构造器
            Constructor constructor= Class.forName(modelClassName).getConstructor();
            
		    while (rs.next()) {
		    	Object object=constructor.newInstance();
		    	Map propertyMap=new HashMap();
		    	for (int i = 0; i < columnCount; i++) {
		    		Object paramValue=new Object();		    				
		    		if(classNames.get(i).equals("java.lang.Integer")){
		    			paramValue=rs.getInt(i+1);
		    		}else if(classNames.get(i).equals("java.lang.String")){
		    			paramValue=rs.getString(i+1);
		    		}
		    		String paramName=rs.getMetaData().getColumnName(i+1);
		    		propertyMap.put(paramName, paramValue);
				}
		    	setValue(object,propertyMap);
		    	list.add((E) object);
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public <E> List<E> selectList(String sqlstring) {
		List<E> list=new ArrayList<E>();
		try {
			Statement statement = connection.createStatement();
			// 准备sql语句,注意: 字符串要用单引号'
			Map map =mapInfo.get(sqlstring);
			String sql=(String) map.get("sql");

			ResultSet rs = statement.executeQuery(sql);
			
	        
			final ResultSetMetaData metaData = rs.getMetaData();
		    final int columnCount = metaData.getColumnCount();
		    for (int i = 1; i <= columnCount; i++) {
		        columnNames.add( metaData.getColumnName(i));
		        classNames.add(metaData.getColumnClassName(i));
		    }
		    
		    String resultType=(String) map.get("resultType");
		    String modelClassName=modelPackage+"."+resultType;
            //构造器
            Constructor constructor= Class.forName(modelClassName).getConstructor();
            
		    while (rs.next()) {
		    	Object object=constructor.newInstance();
		    	Map propertyMap=new HashMap();
		    	for (int i = 0; i < columnCount; i++) {
		    		Object paramValue=new Object();		    				
		    		if(classNames.get(i).equals("java.lang.Integer")){
		    			paramValue=rs.getInt(i+1);
		    		}else if(classNames.get(i).equals("java.lang.String")){
		    			paramValue=rs.getString(i+1);
		    		}
		    		String paramName=rs.getMetaData().getColumnName(i+1);
		    		propertyMap.put(paramName, paramValue);
				}
		    	setValue(object,propertyMap);
		    	list.add((E) object);
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	
	
	public static Object setValue(Object object, Map map) {
		try {
			for (Object key : map.keySet()) {
				Object value =  map.get(key);
				Field f1 = object.getClass().getDeclaredField((String) key);
				f1.setAccessible(true);
				String type = f1.getType().toString();// 得到此属性的类型
				if (type.endsWith("int") || type.endsWith("Integer")) {
					f1.set(object, value);
				} else {
					f1.set(object, value);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}

	public void insert(String string, Object object) {
		try {
			Statement statement = connection.createStatement();
		
			// 准备sql语句,注意: 字符串要用单引号'
			Map map =mapInfo.get(string);
			String sql=(String) map.get("sql");
			
			Field[] field = object.getClass().getDeclaredFields();
			for(int j=0 ; j<field.length ; j++){ //遍历所有属性
		        String name = field[j].getName(); //获取属性的名字
		        //System.out.println("attribute name:"+name);
		        //打开私有访问
		        field[j].setAccessible(true);
		        Object paramValue=field[j].get(object);
		        if(paramValue==null){
		        	paramValue="null";
		        }else{
		        	paramValue="'"+paramValue+"'";	
		        }
		        if(sql.indexOf("#{"+name+"}")==-1){
		        	continue;
		        }
		        sql=sql.replace("#{"+name+"}", paramValue.toString());
			}
			
			statement.execute(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void delete(String string, Object object) {
		insert(string,object);
	}

	public void update(String string, Object object) {
		insert(string,object);
	}

	

}

2.

package com.lc.lcMybatis;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class LcSqlSessionFactoryBuilder {
	
	

	public LcSqlSessionFactory build(InputStream inputStream) {
		LcSqlSessionFactory lcSqlSessionFactory=new LcSqlSessionFactory();
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//实例化DocumentBuilderFactory对象
		DocumentBuilder bulider;
		try {
			bulider = dbf.newDocumentBuilder();
			Document doc = bulider.parse(inputStream);			
			XPathFactory factory = XPathFactory.newInstance();//实例化XPathFactory对象
			XPath xpath = factory.newXPath();
			
			String modelPackage =getModelInfo(xpath,doc);
			lcSqlSessionFactory.setModelPackage(modelPackage);
			String resource =getMapperPath(xpath,doc);
			Map<String, Map<String, String>> mapInfo=getMapperInfo(resource);
			lcSqlSessionFactory.setMapInfo(mapInfo);
			
			//获取数据源的地址,用户名,密码
			XPathExpression compile = xpath.compile("//dataSource");
			NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);
			for(int i=0;i<nodes.getLength();i++) {
		          NodeList childNodes = nodes.item(i).getChildNodes(); //获取一个student节点所有的子节点,返回集合
		          //System.out.println(childNodes.getLength());
		         //遍历所有子节点,获取节点的名称与数据,将其存与Students对象的属性进行匹配并存入到该对象
		          for(int j=0;j<childNodes.getLength();j++) {
			          if(childNodes.item(j).getNodeType() == Node.TEXT_NODE) {
			        		 continue;
			          }
		        	  NamedNodeMap arr = childNodes.item(j).getAttributes();
		        	  //System.out.println(arr.getLength());
		        	  for(int k=0;k<arr.getLength();k++) {
			        	  Node ar = arr.item(k);
			        	  //System.out.println(ar.getNodeName()+"="+ar.getTextContent());
			        	  if(ar.getNodeName().equals("driver")){
			        		  lcSqlSessionFactory.setDriver(ar.getTextContent());
			        	  }else if(ar.getNodeName().equals("url")){
			        		  lcSqlSessionFactory.setUrl(ar.getTextContent());
			        	  }else if(ar.getNodeName().equals("username")){
			        		  lcSqlSessionFactory.setUsername(ar.getTextContent());
			        	  }else if(ar.getNodeName().equals("password")){
			        		  lcSqlSessionFactory.setPassword(ar.getTextContent());
			        	  }
		        	  }
		          }
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lcSqlSessionFactory;
	}

	/**
	 * 获取model的包名
	 * @param xpath
	 * @param doc
	 * @return
	 */
	public static String getModelInfo(XPath xpath,Document doc){
		String modelPackage = null;
		//获取实体类
		try {
			XPathExpression compile = xpath.compile("//typeAliases");
		
			NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);
			NodeList childNodes = nodes.item(0).getChildNodes();
			for(int j=0;j<childNodes.getLength();j++) {
		          if(childNodes.item(j).getNodeType() == Node.TEXT_NODE) {
		        		 continue;
		          }	         
		          NamedNodeMap arr = childNodes.item(j).getAttributes();
		          Node ar = arr.item(0);
		          //System.out.println(ar.getTextContent());
		          modelPackage=ar.getTextContent();
			}
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return modelPackage;
	}
	
	/**
	 * 根据mappers获取mapper。xml路径
	 * @param xpath
	 * @param doc
	 * @return
	 */
	public static String getMapperPath(XPath xpath,Document doc){
		String resource = null;
		//获取实体类
		try {
			XPathExpression compile = xpath.compile("//mappers");
		
			NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);
			NodeList childNodes = nodes.item(0).getChildNodes();
			for(int j=0;j<childNodes.getLength();j++) {
		          if(childNodes.item(j).getNodeType() == Node.TEXT_NODE) {
		        		 continue;
		          }	         
		          NamedNodeMap arr = childNodes.item(j).getAttributes();
		          Node ar = arr.item(0);
		          //System.out.println(ar.getTextContent());
		          resource=ar.getTextContent();
			}
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return resource;
	}
	
	/**
	 * 获取mapper。xml中的信息
	 * @param resource
	 * @return
	 */
	public static Map getMapperInfo(String resource){
		Map<String,Map<String, String>> selectMapperInfo=new HashMap();
		try {
			File f =new File("src/"+resource);
	        //创建基于文件的输入流
	        FileInputStream inputStream = new FileInputStream(f);
	        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//实例化DocumentBuilderFactory对象
			DocumentBuilder bulider = dbf.newDocumentBuilder();
			Document doc = bulider.parse(inputStream);			
			XPathFactory factory = XPathFactory.newInstance();//实例化XPathFactory对象
			XPath xpath = factory.newXPath();
		
			String[] sqltypes={"//select","//insert","//delete","//update"};
			for(String sqltype:sqltypes){
				XPathExpression compile = xpath.compile(sqltype);
				NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);
				for (int index=0;index<nodes.getLength();index++) {
	
					NamedNodeMap namedNodeMap = nodes.item(index).getAttributes();
					Map<String,String> map=new HashMap();
					for(int i=0;i<namedNodeMap.getLength();i++){
	//					System.out.println(namedNodeMap.item(i).getNodeName());
	//					System.out.println(namedNodeMap.item(i).getNodeValue());
						map.put(namedNodeMap.item(i).getNodeName(),namedNodeMap.item(i).getNodeValue());
					}
					map.put("sql",nodes.item(index).getTextContent().replace("\n", "").replace("\t", ""));
					selectMapperInfo.put( namedNodeMap.item(0).getTextContent(),map);
				}	
			}
			
			/*XPathExpression compileSelect = xpath.compile("//insert");
			NodeList nodesSelect = (NodeList)compileSelect.evaluate(doc, XPathConstants.NODESET);
			NamedNodeMap namedNodeMapSelect = nodesSelect.item(0).getAttributes();
			
			Map<String,String> mapSelect=new HashMap();
			mapSelect.put("resultType", namedNodeMapSelect.item(1).getTextContent());
			mapSelect.put("sql",nodesSelect.item(0).getTextContent().replace("\n", ""));
			selectMapperInfo.put( namedNodeMapSelect.item(0).getTextContent(),mapSelect);*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		return selectMapperInfo;
	}
}

3

<mapper>
	<select id="listCategoryByIdAndName"  parameterType="map" resultType="Student">
	    select * from   student  where id> #{id}  and name like concat('%',#{name},'%')
	</select>

	<select id="listStudentByName"  parameterType="string" resultType="Student">
        select * from   student  where name like concat('%',#{0},'%')
    </select>

	<select id="listStudent" resultType="Student">
		select * from   student    
	</select>
	
	<insert id="addStudent">
	    insert into student ( id,name ) values (#{id},#{name})   
	</insert>
	
	<delete id="deleteStudent">
            delete from student where id= #{id}  
    </delete>
    
    <select id="getStudent" resultType="Student">
            select * from   category_  where id= #{id}   
    </select>
    
    <update id="updateStudent">
        update student set name=#{name} where id=#{id}   
    </update>
</mapper>

4.测试

package com.lc;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lc.lcMybatis.LcResources;
import com.lc.lcMybatis.LcSqlSession;
import com.lc.lcMybatis.LcSqlSessionFactory;
import com.lc.lcMybatis.LcSqlSessionFactoryBuilder;
import com.lc.pojo.Category;
import com.lc.pojo.Student;
 
 
public class TestLcMybatis {
 
    public static void main(String[] args) throws IOException {
        String resource = "Lcmybatis-config.xml";
        InputStream inputStream = LcResources.getResourceAsStream(resource);
        LcSqlSessionFactory sqlSessionFactory = new LcSqlSessionFactoryBuilder().build(inputStream);
        LcSqlSession session=sqlSessionFactory.openSession();     
        listAll(session);       
        System.out.println("------------");
        
        
        List<Student> cs = session.selectList("listStudentByName","王");
        for (Student student : cs) {
            System.out.println(student.getName());
        }
        System.out.println("------------");
        
        
        Map<String,Object> params = new HashMap<String, Object>();
        params.put("id", 2);
        params.put("name", "2");   
        List<Student> students = session.selectList("listCategoryByIdAndName",params);
        for (Student student : students) {
            System.out.println(student.getName());
        }
        
    }
    
    public static void listAll(LcSqlSession session){
    	List<Student> cs=session.selectList("listStudent");
        for (Student student : cs) {
            System.out.println(student);
        }
    }
}

5。结果

Student [id=1, name=李四1, sex=男]
Student [id=2, name=王麻子, sex=女]
Student [id=3, name=王麻子2, sex=女]
------------
王麻子
王麻子2
------------
王麻子2

6项目结构

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值