"Rookie Learning Java" 9: Using dom4j parsing Jdbc.xml__java

Source: Internet
Author: User

In the beginning, the program needs to manipulate the database, we will connect the database of the JDBC code into our business logic code, so that every time we connect, we must write a JDBC connection-closed code, such a writing is obviously very bad, once the database has changed, So you're going to be modifying all of the programs in your program that use JDBC, one by one the change is maddening, and batch replacement is not a good way.

So we started with abstraction and encapsulation, extracted the code that connects the database, wrote a tool class, dedicated to maintaining JDBC connection information, and then referenced the JDBC tool class where we were going to connect to the database to complete the database connection and then manipulate the database tables and data. So the problem is, if you want to change the database, then you still have to modify the JDBC Tools class, and recompile, you can complete the database switch, this is not a very clever way.

Finally we came up with the use of XML configuration files to maintain the connection information for JDBC, so that you can read the contents of the configuration file in the JDBC tool class. And the configuration file is to support hot deployment, that is, you can not move any program code, the replacement and modification of the database connection information, it is more fun to do it. Then the question comes again, how to read the configuration file. Please look down.

There are roughly four ways to parse xml: DOM, JDOM, sax, and the dom4j we're going to use right now.

About their introduction and comparison, in this article will no longer elaborate, we can find their own information to learn. Below I will come to the code combat, talk about how to use dom4j parsing XML.

The first step is to prepare a JDBC configuration file Jdbc.xml, as follows:

<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "UTF-8"?>
<config>
	<db-info>
		<driver-name> Oracle.jdbc.driver.oracledriver</driver-name>
		<url>jdbc:oracle:thin: @localhost: 1521:D atabasename</url>
		<user-name>username</user-name>
		<password>password</ password>
	</db-info>
</config></span>

Then prepare an entity class Jdbcconfig.java for easy operation of the parsed JDBC configuration information, as follows:

public class Jdbcconfig {

	private String drivername;
	
	Private String URL;
	
	Private String userName;
	
	private String password;

	Public String Getdrivername () {return
		drivername;
	}

	public void Setdrivername (String drivername) {
		this.drivername = drivername;
	}

	Public String GetUrl () {return
		URL;
	}

	public void SetUrl (String url) {
		this.url = URL;
	}

	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;
	}
	
	@Override public
	String toString () {return
		this.getclass (). GetName () + "{drivername:" + drivername + ", url:" + URL + ", UserName:" + UserName + "}";
	}
	

Then you will write the XML parser, before using dom4j of course to introduce the jar package, as shown in the following figure, the jar package can go to the Internet to download:


The parser Xmlconfigreader.java code is as follows;

/** * Using a single case pattern parsing xml file * @author LJW * * */public class Xmlconfigreader {//lazy (deferred load lazy) private static Xmlconfigrea
	
	Der Instance = null;
	
	Save JDBC related configuration information private jdbcconfig jdbcconfig = new Jdbcconfig ();
		Private Xmlconfigreader () {Saxreader reader = new Saxreader ();
		InputStream in = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream ("Jdbc.xml");
			
			try {Document doc = Reader.read (in);
			Obtain JDBC-related configuration information Element Drivernameelt = (Element) doc.selectobject ("/config/db-info/driver-name");
			Element Urlelt = (Element) doc.selectobject ("/config/db-info/url");
			Element Usernameelt = (Element) doc.selectobject ("/config/db-info/user-name");
			
			Element Passwordelt = (Element) doc.selectobject ("/config/db-info/password");
			Set the JDBC-related configuration Jdbcconfig.setdrivername (Drivernameelt.getstringvalue ());
			Jdbcconfig.seturl (Urlelt.getstringvalue ());
			Jdbcconfig.setusername (Usernameelt.getstringvalue ()); Jdbcconfig.setpassword (Passwordelt.getstringvalue ());
		catch (Documentexception e) {//TODO auto-generated catch block E.printstacktrace (); The public static synchronized Xmlconfigreader getinstance () {if (instance = = null) {instance = new Xmlconfi
		Greader ();
	return instance;
	/** * Returns JDBC related configuration * @return/Public jdbcconfig Getjdbcconfig () {return jdbcconfig;
		public static void Main (string[] args) {Jdbcconfig jdbcconfig = Xmlconfigreader.getinstance (). Getjdbcconfig ();
	System.out.println (Jdbcconfig); }
}

Finally, using the Xmlconfigreader object in the JDBC Tools class to get the JDBC configuration information, the code is as follows

public class Dbutil {

	/**
	 * Obtains Connection * @return * * * public
	static Connection getconnection () {
		Connection conn = null;
		try {
			Jdbcconfig jdbcconfig = Xmlconfigreader.getinstance (). Getjdbcconfig ();
			Class.forName (Jdbcconfig.getdrivername ());
			conn = Drivermanager.getconnection (Jdbcconfig.geturl (), Jdbcconfig.getusername (), Jdbcconfig.getpassword ());
		catch (ClassNotFoundException e) {
			e.printstacktrace ();
		} catch (SQLException e) {
			e.printstacktrace () ;
		}
		return conn;
	}
	
	public static void Main (string[] args) {
		System.out.println (dbutil.getconnection ());
	}

        Summary:         dom4j is a very, very good Java XML API with excellent performance, powerful and extremely easy-to-use features, and it is also an open source software. Now you can see that more and more Java software is using dom4j to read and write XML, especially even Sun JAXM is using dom4j, and the famous hibernate uses it to read XML configuration files.

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.