20145326 "Java program design" The 9th Week study summary Textbook Learning content Summary
16th Chapter
I. Getting Started with JDBC
1.JDBC Introduction
JDBC is a solution for executing SQL, the developer uses the standard interface of JDBC, the database vendor operates on the interface, the developer does not have to touch the difference of the underlying database driver, and the database itself is a standalone application. The application you write is to use the communication protocol to exchange the database for instructions, for the data to be deleted and searched. Typically, your application uses a set of linked libraries that specifically communicate with the database to simplify the process of writing to the database. Sometimes, the need to replace a database is not without, and application cross-platform is often a requirement, and JDBC is basically used to solve these problems. JDBC is the standard specification for Java online databases. Specifically, it defines a set of standard classes and interfaces that the application requires when the online database is called, while the interfaces in the standard API are operated by the database vendor, often referred to as the JDBC driver. The JDBC standard consists of two parts: the JDBC Application developer interface and the JDBC driver developer interface. If your application requires an online database, it is called the JDBC Application developer interface, the API is primarily in java.sql and javax.sql two packages, and the JDBC driver developer Interface is the specification of the database vendor operating driver. If there is a program code, it is the role of the online MySQL database, you need to set the JDBC driver in classpath, specifically, in the classpath to set a jar document, if you want to replace the Oracle database, as long as the replacement of the Oracle driver , specifically, the jar document that was changed to the Oracle driver in Classpath, but the application itself is not modified. What JDBC wants to achieve is that Java programmers can have a unified interface when composing database operations, without relying on the API of a particular database, in order to "write a Java program, manipulate all Databases". When operating the JDBC driver, the manufacturer can be divided into four types: (1) jdbc-odbc Bridge Driver, which is a Microsoft-led database Connectivity Standard, basically JDBC is a reference to ODBC, So ODBC is the most mature on Microsoft systems, but because JDBC does not correspond to ODBC one by one, some calls cannot be converted directly, so the ODBC driver itself has a cross-platform limitation. (2) Native API Driver, this type of driver will be in the native way, call the database provided by the native link library, at a speed of 4 types of the fastest, but not cross-platform. (3) Jdbc-net Driver, this type of JDBC driver transforms a JDBC method call into a specific networkNetwork protocol, which is highly elastic and has a cross-platform nature. (4) Native Protocol Driver, this way can be cross-platform, performance also has a good performance, when not required as (3) to obtain architectural flexibility, usually use this type of driver, is the most common driver type.
2. Connect to the database
In order to connect to the database system, a vendor-operated JDBC driver must be required, and the driver jar document must be set in Classpath.
3. Using statement, ResultSet
Connection is the representative object of the database connection, the next thing to do is to execute the SQL, you must get the Java.sql.Statement action object, which is the representative object of SQL description. Statement's execute () can be used to execute SQL, and can test whether SQL is executing a query or an update, and returning TRUE indicates that SQL execution will return resultset as the result of the query. Depending on the requirements, statement or resultset can be closed using close () when not in use to release the associated resources. When the statement is closed, the associated resultset is also automatically closed.
4. Using PreparedStatement, CallableStatement
If some of the operations are just some of the parameters in the SQL statement, and the rest of the SQL clauses are the same, you can use Java.sql.PreparedStatement. You can use the connection PreparedStatement () method to build a precompiled SQL statement, where the parameters change, specifying the "? "This placeholder character. In JDBC to represent the date, is to use java.sql.Date, its date format is "year, month, day", to indicate the time is the use of java.sql.Time, its time format is "hours, minutes, seconds", if you want to represent "hours, minutes, seconds, microseconds" format, You can use Java.sql.Timestamp.
Second, JDBC Advanced
1. Scrolling and updating data with ResultSet
When resultset, the default is to use Next () to move the data cursor to the next data, and then use the GetXXX () method to get the data. The result set type can specify 3 settings: Resultset.typeFORWARDonly (default), Resultset.typeSCROLLinsensitive, Resultset.type SCROLLsensitive. The update settings can be specified in two ways: Resultset.concurREADonly (default), Resultset.concur_updatable. If you want to use resultset for data modification, there are some limitations: a single table must be selected, a primary key must be selected, and all values that are NOT NULL must be selected.
2. Batch Update
Every execution of executeupdate (), in fact, will send a SQL to the database, if a large number of updated SQL has 10,000, it is equal to 10,000 times through the network of information transmission, network transmission information must actually open I/O, Routing and other actions. So it's best to have all of the SQL collected, and then string to a SQL, and then to the database, since the batch update, as the name implies, is only used on the update, so the limit of the batch update is that SQL cannot be a select, otherwise it throws an exception.
3.Blob and Clob
If you are writing a document to a database, you can use a BLOB or CLOB data type on a database table field, where BLOBs are used to store large amounts of binary data, such as drawings, audio files, and so on, and Clob are used to store large amounts of literal data.
4. Trading Profile
The four basic requirements of trading are atomicity, consistency, isolation, and continuity of behavior. What are the possible data inconsistencies that can arise when multiple transactions are in parallel? (1) Update lost: basically refers to a transaction to update the field information, due to the intervention of another transaction lost the effectiveness of the update. (2) Dirty read: When two transactions are in progress, one transaction updates the data but is not confirmed, and the other transaction reads the data, and a dirty read problem may occur. (3) cannot read repeatedly: A transaction two times the data in the same field is not consistent. (4) Phantom reading: The number of data strokes that are read is inconsistent during the same transaction.
5.metadata Introduction
Metadata is the "data of the reading data", where the database is used to store data, but what is the name of the product in the database itself? How many data tables are in the database? What is the name of the table? How many fields are there in the table? These are all metadata.
6.RowSet Introduction
JDBC defines the Java.sql.RowSet interface, which represents the collection of columns of data, which is not necessarily data in the database, but can be spreadsheet data, XML data, or any data source with the concept of a column collection. Rowset defines the basic behavior of the column collection, which has the Jdbcrowset, CachedRowSet, Filteredrowset, Joinrowset, and Webrowset Five standard column set sub-interfaces. Jdbcrowset is an online rowset, that is, during the operation Jdbcrowset, is kept online with the database, can be considered as acquisition, Operation ResultSet behavior encapsulation, can simplify the composition of the JDBC program, or as a JavaBean use. CachedRowSet is an offline rowset, when the data is queried and populated, it is disconnected from the data source without taking up the relevant online resources and, if necessary, synchronizing with the data source online.
17th Chapter
First, the use of reflection
1. Reflection
When we use a class, if the class has not yet been loaded into memory, the system initializes the class by loading, joining, initializing.
Second, understand the class loader
1. Class Loader Hierarchical architecture
Class loading refers to reading class files of classes into the JVM and creating a class object for it. Class join refers to merging the binary data of the class into the JRE, which is divided into 3 stages: (1) Check: Checking the correctness of loading class file data. (2) Preparation: Allocates storage space for static variables of the class and initializes it by default. (3) Parsing: Replace the symbolic reference in the binary data of the class with a direct reference. Initialization refers to the initialization of static variables and static initialization blocks of a class.
Attention:
A. A static property of a final type, if the property value has been obtained at compile time, then calling the property does not cause the class to initialize because it is equivalent to using a constant.
B. Using the ClassLoader () method, just load the class, not initialized.
The ClassLoader is responsible for loading the. class file into memory and generating the corresponding Java.lang.Class object for it, which is responsible for loading all classes, and once a class is loaded into the JVM, it will not be loaded again. In Java, a class is identified with its fully qualified class name (that is, the package name + class name). The JVM runtime generates 3 ClassLoader: Bootstrapclassloader (Root ClassLoader), extclassloader (extension ClassLoader), and Appclassloader (System ClassLoader).
Where Bootstrapclassloader is responsible for loading the JRE's core class library, which is not a subclass of ClassLoader, written in C + +, so we do not see it in Java, and when obtained by its subclass's GetParent () method, returns NULL, Bootstrapclassloader is responsible for loading Java core class libraries such as Rt.jar and Charsets.jar under the JRE target.
18th Chapter
One, custom generics
1. Generics
Before the JDK1.5 version, if different types of data were added to the collection, the conversion between the types needs to be checked during the program's run.
For example:
List arraylist=new arrayList ();
Add the String type Object and the integer object in ArrayList, but we define an array of string[] values=new string[arraylist.size ()]; If you want to convert arrayList to an array, an error occurs: Arraylist.toarray (values);//run-time error.
This is because the list contains an integer wrapper type object. However, this error can only be found during runtime, the program can be compiled normally, and will not error. For errors in the program, you should notify the programmer as soon as possible. Generics are a good way to solve this problem.
Generics are applied in collections: Java provides support for generics after the JDK1.5 version. For example, for a ArrayList list, if you just want to put a string type element in the list, you can do so in the following way: ArrayList list=new ArrayList ();
Generics allow the compiler to check the objects that are added to the collection during compilation, and if different types of objects are added, an error occurs without having to wait for the related type conversions during the run. Compared with the original is not using generics, it will need to be in the runtime to find exceptions early to the compilation period, so that the security of the program is greatly improved, generics are generally used in the collection class.
Second, enumeration
1. Enumeration type
Enumerations are also features that are newly added to Java after the JDK1.5 version. An enumeration can be used to represent a set of constant data. The essence of an enumeration is a class that declares an enumeration type by using the enum keyword, which is declared as follows: [Access control] enum enum type name {value1,value2,......} Use enumeration types to be aware of the following points:
A. Enumeration types can be defined inside a class or outside of a class. If defined inside a class, the access control can be either public,protected,private or the default control character. If the definition is outside the class, its access/ask control can only be public and the default control character;
B. The value values defined in the enumeration type are default to public static final. Once the value is defined, it cannot be modified. Multiple value values need to be separated by commas;
C. Enumeration types can also declare methods in addition to declaring constants. However, the method needs to be followed by a constant, and the constants and methods should be separated by semicolons;
D. Values in enumerated types can be accessed directly by enumerating the type names;
E. Enumeration types cannot be declared as abstract or final type;
Operation Result:
2. Common methods for enumeration types
Public final String name ()//returns the name of the enumeration constant; public final int ordinal ()//returns the position of the enumeration constant in the enumeration type, the first enumeration value ordinal is 0, and so on; public String ToString ()//returns the name of the enumeration constant, which can override this method; public static valueOf (enumtype,string name)//Returns the enumeration constant corresponding to the name
Operation Result:
Third, comments
1. Annotation types
Use annotations in the source code, provide additional compilation hints to the compiler, or provide configuration information that can be read at the time of application execution. Comments can be used only for the original code, and the. Class document is compiled to be read only by the compiler or during open execution time.
2. Common standard Annotations
@Override//is the standard comment, the annotated method must be a method that is already defined in the parent class or interface, and the compiler assists in the process of actually redefining the method. @Deprecated//If a method originally existed with the API and is not recommended for reuse later, you can comment on the method. If a user subsequently wants to invoke or redefine this method, the compiler will warn you. For APIs that support generics, it is recommended to explicitly specify a generic true type, and if not specified, the compiler warns. @SuppressWarnings//Specify a warning to suppress unchecked: @SuppressWarnings (value={"Unchecked"}) @SafeVarargs//indicates that the developer has determined to avoid the heap Pollution problem. The problem with heap pollution is that the compiler cannot check the execution period for type errors and cannot specifically confirm the argument type. @FunctionalInterface//Let the compiler assist in checking whether interface can be used as the target type of the lambda custom annotation type • Mark comments: Just the comment name itself is the information, for the compiler or application, the main is to check whether there are comments appear, and make the corresponding action. • Related rules:
(1) If the comment name itself cannot provide enough information, set a single-value comment
(2) Note Attributes can also be specified in an array form.
(3) When defining annotation properties, if the property name is value, you can omit the property name and specify the value directly.
(4) Set the default value for the member and use the Defaults keyword.
(5) To set the array default value, you can add {} after default, and you can place the element value in {} if necessary.
When you define annotations, you can specify Java.lang.annotation.ElementType enumeration values when you use Java.lang.annotation.Target qualification. When you make a Javadoc file, the annotation data is not added to the file by default, and you can use java.lang.annotation.Documented if you want to add the comment data to the file. Annotations that are set by the default parent class are not inherited to subclasses, and when you define a comment, you set the java.lang.annotation.Inherited comment to allow the annotation quilt class to inherit.
3.jdk8 Labeling Enhancements
An enumeration member of the A.elementtype is used to qualify which declaration position can be labeled. In JDK8, two enumeration members of type _parameter, type _use are added.
B.elementtype.type _ use can be used for labeling in various types, a label if it is set elementtype.type_use, as long as the type name, can be labeled.
[Email protected] allows you to repeat the same label in the same place
[email protected] as a container for collecting duplicate callout information, and each @filters stores the specified string value. Read comment information during execution
4. Custom annotations
The default is to store the comment information in a. class document, which can be read by the compiler or the Code analysis tool, but cannot read the comment information during the execution period and read the annotation information during the execution time, which can be used with java.lang.annotation.Retention java.lang.annotation.Re Tentionpolicy enumeration specified. The timing of retentionpolicy for runtime is to allow annotations to provide application information during execution, and to use the Java.lang.reflect.AnnotatedElement interface to manipulate objects to obtain annotation information. The new Getdeclaredannotation (), Getdeclaredannotationsbytype (), Getannotationsbytype () Three methods are added in JDK 8. Getdeclaredannotation () allows you to retrieve the specified callout, and when you specify a callout for @repeatable, you look for a container that collects duplicate labels. Getdeclaredannotationsbytype (), Getannotationsbytype () will not process the @repeatable tag.
Code hosting:
Number of lines of code: