Spring configuration file XML implementation ICO_IOC configuration file injection

Source: Internet
Author: User
Tags stmt stub

Item: Implementation of the user table and additions and deletions to check

Project structure at a glance:


First create the corresponding user table

DROP TABLE IF EXISTS ' user ';
CREATE TABLE ' user ' (
  ' id ' int () NOT NULL auto_increment,
  ' username ' varchar ' is not NULL,
  ' password ' varch AR not null,
  ' sex ' varchar default null,
  ' realname ' varchar default NULL,
  PRIMARY KEY (' id ')
) Engine=innodb auto_increment=12 DEFAULT Charset=utf8;

According to the user table, Create the corresponding entity class (Com.hpe.po.User) where the name of the table field is the same as the Entity Class Property name (the Get,set method must be in accordance with the Bean's specification, and the parameterless construction method is required, and the corresponding bean is created according to the parameterless construction method when mxl the file Management Bean):

public class User {private int id;
	Private String username;
	private String password;
	Private String realname;
	Private String sex;
	Public User () {super ();
		public User (int ID, string username, string password, string realname, String sex) {super ();
		This.id = ID;
		This.username = Username;
		This.password = password;
		This.realname = Realname;
	This.sex = sex;
	public int getId () {return id;
	The public void setId (int id) {this.id = ID;
	Public String GetUserName () {return username;
	} public void Setusername (String username) {this.username = username;
	Public String GetPassword () {return password;
	} public void SetPassword (String password) {this.password = password;
	Public String Getrealname () {return realname;
	} public void Setrealname (String realname) {this.realname = Realname;
	Public String Getsex () {return sex;
	} public void Setsex (String sex) {this.sex = sex; @Override public String toString () {return "User [id= + ID +", username= "+ Username +", password= "+ password +", realname= "+ Realname +", sex= "+ Sex +
	"]"; }

To create an interface to a database operation under Com.hpe.dao:

Public interface Iuserdao {
	user fnduserbynameandpwd (user user);
	int register (user user);
	int Checkusername (String Username);
	List<user> SelectAll ();
	int Deletebyid (int id);
	List<user> Selectmohu (String username);

Implement Interface (COM.HPE.DAO.IMPL) according to the interface method:

Package Com.hpe.dao.impl;

Import java.util.List;
Import Com.hpe.dao.IUserDao;
Import Com.hpe.po.User;

Import Com.hpe.util.DBUtil;
	public class Userdaoimpl implements iuserdao{private Dbutil db=new dbutil (); @Override Public user fnduserbynameandpwd (user user) {String sql= ' select * from User where username=? and password=? '
		;
		Object[] Params={user.getusername (), User.getpassword ()};
		User us=db.getobject (SQL, Params,user.class);
	return us;  @Override public int Register (user user) {String sql= ' insert into User (username, password, sex, realname) values (?,
		?,?,?)";
		Object[] Params={user.getusername (), User.getpassword (), User.getsex (), User.getrealname ()};
		int res=db.update (SQL, params);
	return res; @Override public int Checkusername (string username) {string sql= ' select * from user where username=?
		";
		Object[] Params={username};
		
		list<user> list= db.query (sql, params, user.class);
	return List.size (); } @Override public list<user> SELectall () {String sql= ' select * from user ';
	
		Object[] params={};
	return db.query (SQL, params, user.class);
		@Override public int Deletebyid (int id) {String sql= ' delete from user where id=? ';
		Object[] Params={id};
	return db.update (SQL, params); @Override Public list<user> Selectmohu (string username) {string sql= ' select * from User where username like
		'% ' +username+ '% ';
		Object[] params={};
		
		list<user> list= db.query (sql, params, user.class);
	return list; }

}

There are a variety of Dao.impl connection database methods, the utility of which is JDBC, which encapsulates the database connection in the tool class.

Tools list:

Package com.hpe.util;
Import Java.beans.BeanInfo;
Import java.beans.IntrospectionException;
Import Java.beans.Introspector;
Import Java.beans.PropertyDescriptor;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
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 Javax.management.Query;
		public class Dbutil {//Load database driver, create connection object and return to public Connection Getconn () throws ClassNotFoundException, SQLException {

		The class with the specified name is loaded through the class loader (ClassLoader) to the JVM (Java Virtual machine) Class.forName ("Com.mysql.jdbc.Driver");
		String url = "Jdbc:mysql://127.0.0.1:3306/mybatis?useunicode=true&characterencoding=utf-8";
		String user = "root";

		String pwd = "";

		Connection conn = drivermanager.getconnection (URL, user, pwd); /*
		 * 
		 * 1. Load Drive 2. Create a Connection object//After three times handshake 3. Create execution Object 4. Execute SQL 5. Processing returns a result of 6. Release Resources/* After four handshake * * data connection pool: In a container-> pool, create a certain data connection object, the application needs to connect objects, directly from the container, after use, * and then put the connection object back to the container, instead of straight
		 Connect Close.
	* * Return conn;
			}//Free resources resultset statement Connection public void Close (ResultSet RS, statement stmt, Connection conn) {try {
			if (Rs!= null) {rs.close ();
		} catch (SQLException e) {e.printstacktrace ();
			try {if (stmt!= null) {stmt.close ();
		} catch (SQLException e) {e.printstacktrace ();
			try {if (conn!= null) {conn.close ();
		} catch (SQLException e) {e.printstacktrace (); } public Map GetObject (String sql, object[] params) {//Get query Results list list<map<string, object>> list = q

		Uery (sql, params);
		Returns only the first if (List.size () > 0) {return list.get (0);
		else {return null; } public <T> T getObject (String sql, object[] params, class<t> CLS) {//query out a record map map = GetObject (sql, params);
	Converts a map to an entity class object return (T) toobj (map, CLS); //Get multiple objects, save each object in a Map, and save multiple objects to List public list<map<string, object>> query (String sql, object[] p
		Arams) {Connection conn = null;
		PreparedStatement stmt = null;

		ResultSet rs = null;

		list<map<string, object>> list = new arraylist<> ();
			try {conn = Getconn ();

			stmt = conn.preparestatement (sql); When the parameter array is not empty, the argument is bound, this sentence must have, otherwise params.length will report nullpointerexception if (params!= null) {//for (int i = 0; i < Params.length;
				i++) {Stmt.setobject (i + 1, params[i]);

			}//rs = Stmt.executequery ();
				while (Rs.next ()) {//Because the query may be for different tables, different table structures are not the same. Can there be a unified data type that can receive this variable data? * * * Map interface holds multiple data in Key-value * * * HashMap/hashmap<string, object> map = new has

				Hmap<> ();

				int colcount = Rs.getmetadata (). getColumnCount (); for (int i = 1; I <= colcount; i++) {String colname = Rs.getmetadata (). getColumnName (i);

					Object value = Rs.getobject (colname);
				Map.put (colname, value);

				//The map of a single record is placed in an array.
			List.add (map);

		//Returns the array return list;
		catch (ClassNotFoundException e) {e.printstacktrace ();
		catch (SQLException e) {e.printstacktrace ();
		Finally {close (RS, stmt, conn);
	return null; } public <T> list<t> query (String sql, object[] params, class<t> cls) {list<map<string, objec

		t>> list = query (sql, params);

		list<t> res = new arraylist<> ();

			For (map<string, object> map:list) {T obj = toobj (Map, CLS);
		Res.add (obj);
	return res; Create T obj = cls for private <T> T Toobj (map<string, object> Map, class<t> cls) {try {//Entity class object.

			Newinstance ();
			Setting the data in the map into obj//BeanInfo is a class-related information BeanInfo info = introspector.getbeaninfo (CLS); Get information for each property of a class propertydescriptor[] Properties = Info.getpropertydescriptors (); for (PropertyDescriptor prop:properties) {//Get the name of the property String propname = Prop.getname ();//-> name//acquire genus The set method of sex is a setter = Prop.getwritemethod ();

				-> SetName (String);

				Remove the value of the attribute in the map, Object value = Map.get (propname);
					if (value!= null) {//Call Setter Set value try {//Entity class property setting Setter.invoke (obj, value);
					catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace ();
					catch (InvocationTargetException e) {//TODO auto-generated catch block E.printstacktrace ();

		}} return obj;
		catch (Instantiationexception e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (Introspectionexception e) {//TODO auto-generated catch block E.printstacktrace (); return null;
	public int update (String sql, object[] params) {Connection conn = null;
		PreparedStatement stmt = null;
		int res = 0;
		ResultSet rs = null;
			try {conn = Getconn ();

			stmt = conn.preparestatement (sql, Com.mysql.jdbc.Statement.RETURN_GENERATED_KEYS); When the parameter array is not empty, the argument is bound, this sentence must have, otherwise params.length will report nullpointerexception if (params!= null) {//for (int i = 0; i < Params.length;
				i++) {Stmt.setobject (i + 1, params[i]);
			}//Res = stmt.executeupdate ();
			rs = Stmt.getgeneratedkeys ();
			if (Rs.next ()) {res = Rs.getint (1);
		} catch (ClassNotFoundException e) {e.printstacktrace ();
		catch (SQLException e) {e.printstacktrace ();
		Finally {close (RS, stmt, conn);
	return res; }
}


Then we create the service, (Com.hpe.service):

Package com.hpe.service;

Import java.util.List;

Import Com.hpe.po.User;

Public interface Iuserservice {
	User login (user user);
	int register (user user);
	List<user> SelectAll ();
	int Deletebyid (int id);
	List<user> Selectmohu (String username);

Implement service (COM.HPE.SERVICE.IMPL.USERSERVICEIMPL), note that we are no longer Iuserdao iud=new Userdaoimpl when invoking the DAO interface, this way, Instead, the Iuserdao is handed to the configuration file management, and the bean is used to pass the parameters according to the set method.

Package Com.hpe.service.impl;

Import java.util.List;
Import Com.hpe.dao.IUserDao;
Import Com.hpe.dao.impl.UserDaoImpl;
Import Com.hpe.po.User;

Import Com.hpe.service.IUserService; The public class Userserviceimpl implements iuserservice{private Iuserdao iud;//ioc control inversion, with the configuration file to manage the Iuserdao implementation class, so here to give the variable, In the configuration file implementation//set method must have, IOC control reversal, profile management bean, create Iuserdao entity class, when property settings properties, will mobilize the set method here, will create the//iuserdao iud=new
	The Userdaoimpl () entity class uses the Set method, which is called here Setiud (), to assign values to the Iuserdao IUD declared here. Corresponding profile: <bean id= "UserService" class= "Com.hpe.service.impl.UserServiceImpl" >//<property name= "IUD" ref= "
	Userdao "></property>//</bean> public void Setiud (Iuserdao IUD) {this.iud = IUD; @Override Public User Login (user user) {//TODO auto-generated a stub return iud.fnduserbynameandpwd
	R);
	@Override public int Register (user user) {//TODO auto-generated a stub return iud.register (user); @Override public list<user> SelectAll () {//TOdo auto-generated Method stub return Iud.selectall ();
	@Override public int Deletebyid (int id) {//TODO auto-generated a stub return Iud.deletebyid (ID); @Override public list<user> Selectmohu (String username) {//TODO auto-generated a stub return Iud.sel
	Ectmohu (username); }

	
}

The

is not a bit of a Meng. Look at the configuration file and you'll see

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:util= " Http://www.springframework.org/schema/util "xsi:schemalocation=" Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http:// Www.springframework.org/schema/util/spring-util.xsd "> <!--inject a class of bean,bean tag management, which is equivalent to automatically calling an parameterless constructor to create an entity class, When the new Userdaoimpl (), the ID here is convenient for the call to recognize the bean, arbitrary name, but to be meaningful. --> <bean id= "Userdao" class= "Com.hpe.dao.impl.UserDaoImpl" ></bean> <!--injection Application type--> <!--call has the reference structure The builder constructs the Userserviceimpl class that the Bean manages, equivalent to the new Userserviceimpl (Property1,property2,...)--> <bean id= "UserService" class = "Com.hpe.service.impl.UserServiceImpl" > <!--a parameter description of the parameters constructor, name is the parameter name of the parameter constructor,
Value is a parameter value. Here the parameter value is also a class object, so we use ref, in order to be			 The Bean entity class that ref equals to create objects that can be reused, ref= "The ID of a bean", and the Id=userdao bean is the object that creates the Userdaoimpl's parameterless construction method. --> <property name= "IUD" ref= "Userdao" ></property> <!--<property name= "IUD value=" Com.hpe.dao. Impl. Userdaoimpl "></property>--> </bean> </beans>

Finally, we create the test class under the Com.hpe.test package, using the JUnit test

Package com.hpe.test;

Import java.util.List;
Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import Com.hpe.dao.IUserDao;
Import Com.hpe.dao.impl.UserDaoImpl;
Import Com.hpe.po.User;

Import Com.hpe.service.IUserService; public class Usertest {@Test public void method1 () {//loading configuration file, initializing IOC container (creating corresponding instance) ApplicationContext context = new C
		
		Lasspathxmlapplicationcontext ("Applicationcontext.xml");
		Gets the bean iuserservice UserService = Context.getbean from the IOC container ("UserService", Iuserservice.class); By Getbean, the implementation class for the Iuserserviceimpl of the UserService ID is read (in the Bean label, class is set to Userserviceimpl.)
		So get the implementation class)//Then the bean sets the properties, the Propert tab, set the property field in Userserviceimpl Userdao as the entity for the Userdaoimpl implementation class.
		User User=new user ();
		User.setusername ("YJZ");
		User.setpassword ("123");
	System.out.println (userservice.login (user)); @Test public void Method2 () {//Load configuration file, initialize IOC container (create corresponding instance) ApplicationContext conText = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
		Gets the bean iuserservice UserService = Context.getbean from the IOC container ("UserService", Iuserservice.class); By Getbean, the implementation class for the Iuserserviceimpl of the UserService ID is read (in the Bean label, class is set to Userserviceimpl.)
		So get the implementation class)//Then the bean sets the properties, the Propert tab, set the property field in Userserviceimpl Userdao as the entity for the Userdaoimpl implementation class.
		User User=new user ();
		User.setusername ("YJZ");
		User.setpassword ("123");
		List<user> List=userservice.selectall ();
		for (User u:list) {System.out.println (U); @Test public void Method3 () {//Load configuration file, initialize IOC container (create corresponding instance) ApplicationContext context = new Classpathxmlapplica
		
		Tioncontext ("Applicationcontext.xml");
		Gets the bean iuserservice UserService = Context.getbean from the IOC container ("UserService", Iuserservice.class); By Getbean, the implementation class for the Iuserserviceimpl of the UserService ID is read (in the Bean label, class is set to Userserviceimpl.)
		So get the implementation class)//Then the bean sets the properties, the Propert tab, set the property field in Userserviceimpl Userdao as the entity for the Userdaoimpl implementation class. System.out.println (Userservice.deletebyId (8)); @Test public void Method4 () {//Load configuration file, initialize IOC container (create corresponding instance) ApplicationContext context = new Classpathxmlapplicationc
		
		Ontext ("Applicationcontext.xml");
		Gets the bean iuserservice UserService = Context.getbean from the IOC container ("UserService", Iuserservice.class); By Getbean, the implementation class for the Iuserserviceimpl of the UserService ID is read (in the Bean label, class is set to Userserviceimpl.)
		So get the implementation class)//Then the bean sets the properties, the Propert tab, set the property field in Userserviceimpl Userdao as the entity for the Userdaoimpl implementation class.
		User User=new user ();
		User.setusername ("yjz222");
		User.setpassword ("123");
		User.setrealname ("ASDASD");
		User.setsex ("male");
		
		System.out.println (userservice.register (user)); @Test public void Method5 () {//Load configuration file, initialize IOC container (create corresponding instance) ApplicationContext context = new Classpathxmlapplicationc
		
		Ontext ("Applicationcontext.xml");
		Gets the bean iuserservice UserService = Context.getbean from the IOC container ("UserService", Iuserservice.class); By Getbean, the implementation class for the Iuserserviceimpl of the UserService ID is read (in the Bean label, class is set to Userserviceimpl.) So get the implementation class)//Then the Bean sets the property,The Propert tab, which sets the property field in Userserviceimpl Userdao as the entity for the Userdaoimpl implementation class.
		List<user> List=userservice.selectmohu ("Y");
		for (User u:list) {System.out.println (U);
 }
	}
}







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.