search
HomeJavajavaTutorialNew Java Movement: Test Driven Development 3---User Registration 3

Up to now, we have not touched on the substantive issue of user registration, that is, adding users to the database. Let's deal with this requirement now.

First you need to determine the technology used for database access. You can choose Hibernate, JPA or JDBC here. I believe that the vast majority of applications use Hibernate as the database access technology. Others may choose JPA, but we choose JDBC here. The reason is relatively simple. The underlying things seem to be more complicated, but once mastered, it is relatively easier to master because of its less content. This O-R mapping model adds many abstract concepts and details. We usually only look at the tip of the iceberg of these architectures. If you want to master the things under the iceberg, the difficulty is several orders of magnitude more difficult than directly mastering JDBC.

In addition, due to our test-driven development architecture, if we want to convert to other architectures, we can refactor the existing code. Under the guarantee of test cases, we can safely modify the code.

Okay, we first use the DAO mode to define the database access interface class UserDao. The code is as follows:

public interface UserDao {  
    public long registerUser(Map<String, Object> userInfo);  
}

Generally speaking, we use the Mysql database, so we define the Dao implementation class UserMysqlDao , the code is as follows:

public class UserMysqlDao implements UserDao {  
    @Override  
    public long registerUser(Map<String, Object> userInfo) {  
        // TODO Auto-generated method stub  
        return 0;  
    }

Of course we do not want the user to determine the database used, and then instantiate the corresponding implementation class. For this reason, we need to adopt the factory mode and introduce the DaoFactory class. The code is as follows:

public class DaoFactory {  
    public static UserDao getUserDao() {  
        UserDao dao = null;  
        switch (dbms) {  
        case "mysql":  
            dao = new UserMysqlDao();  
            break;  
        }  
        return dao;  
    }  
      
    public static String getDbms() {  
        return dbms;  
    }  
  
    public static void setDbms(String dbms) {  
        DaoFactory.dbms = dbms;  
    }  
  
    private static String dbms = "mysql";  
}

As can be seen from the above code, the caller only needs to call DaoFactory.getUserDao() to obtain the implementation class.

The following is the problem of database connection. We hope to use the database connection pool when running on application servers such as Jboss, and use DriverManager in unit testing, so we need to define a DataSource encapsulation class JdbcDs to handle the above situation. The code is as follows:

public class JdbcDs {	
	public static Connection getConnection() throws SQLException {
		Connection conn = null;
		if (iDebug <= 0) {
			conn = appDs.getConnection();
		} else {
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Properties connectionProps = new Properties();
		    connectionProps.put("user", "root");
		    connectionProps.put("password", "yantao");
		    conn = DriverManager.getConnection(
	                   "jdbc:" + "mysql" + "://" +
	                   "localhost" +
	                   ":" + 3306 + "/XrcjDb",
	                   connectionProps);
		}
		return conn;
	}

	public static int iDebug = 1;
	public final static String APP_DS = "java:jboss/datasources/XcgDS";
	private static DataSource appDs = null; 
	static{
		if (null == appDs) {
			Properties env = new Properties();
			try {
				InitialContext ictx = new InitialContext(env);
				appDs = (DataSource)ictx.lookup(APP_DS);
			} catch (NamingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
}

When doing unit testing, just set iDebug to 1. Otherwise the database connection pool will be used.

After all the preparation work is done, the database function development can be officially carried out.

The above is the content of the New Java Movement: Test Driven Development 3---User Registration 3. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools