Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
src/main/asciidoc/jpa.adoc
### 代码内容：
[[jpa.repositories]]
= JPA Repositories

This chapter will point out the specialties for repository support for JPA. This builds on the core repository support explained in <<repositories>>. So make sure you've got a sound understanding of the basic concepts explained there.

[[jpa.introduction]]
== Introduction

[[jpa.namespace]]
=== Spring namespace

The JPA module of Spring Data contains a custom namespace that allows defining repository beans. It also contains certain features and element attributes that are special to JPA. Generally the JPA repositories can be set up using the `repositories` element:

.Setting up JPA repositories using the namespace
====
[source, xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <jpa:repositories base-package="com.acme.repositories" />

</beans>
----
====

Using this element looks up Spring Data repositories as described in <<repositories.create-instances>>. Beyond that it activates persistence exception translation for all beans annotated with `@Repository` to let exceptions being thrown by the JPA persistence providers be converted into Spring's `DataAccessException` hierarchy.

==== Custom namespace attributes
Beyond the default attributes of the `repositories` element the JPA namespace offers additional attributes to gain more detailed control over the setup of the repositories:

.Custom JPA-specific attributes of the repositories element
[options = "autowidth"]
|===============
|`entity-manager-factory-ref`|Explicitly wire the `EntityManagerFactory` to be used with the repositories being detected by the `repositories` element. Usually used if multiple `EntityManagerFactory` beans are used within the application. If not configured we will automatically lookup the `EntityManagerFactory` bean with the name `entityManagerFactory` in the `ApplicationContext`.
|`transaction-manager-ref`|Explicitly wire the `PlatformTransactionManager` to be used with the repositories being detected by the `repositories` element. Usually only necessary if multiple transaction managers and/or `EntityManagerFactory` beans have been configured. Default to a single defined `PlatformTransactionManager` inside the current `ApplicationContext`.
|===============

Note that we require a `PlatformTransactionManager` bean named `transactionManager` to be present if no explicit `transaction-manager-ref` is defined.

[[jpa.java-config]]
=== Annotation based configuration
The Spring Data JPA repositories support cannot only be activated through an XML namespace but also using an annotation through JavaConfig.

.Spring Data JPA repositories using JavaConfig
====
[source, java]
----
@Configuration
@EnableJpaRepositories
@EnableTransactionManagement
class ApplicationConfig {

  @Bean
  public DataSource dataSource() {

    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    return builder.setType(EmbeddedDatabaseType.HSQL).build();
  }

  @Bean
  public EntityManagerFactory entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.acme.domain");
    factory.setDataSource(dataSource());
    factory.afterPropertiesSet();

    return factory.getObject();
  }

  @Bean
  public PlatformTransactionManager transactionManager() {

    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory());
    return txManager;
  }
}
----
====

The just shown configuration class sets up an embedded HSQL database using the `EmbeddedDatabaseBuilder` API of spring-jdbc. We then set up a `EntityManagerFactory` and use Hibernate as sample persistence provider. The last infrastructure component declared here is the `JpaTransactionManager`. We finally activate Spring Data JPA repositories using the `@EnableJpaRepositories` annotation which essentially carries the same attributes as the XML namespace does. If no base package is configured it will use the one the configuration class resides in.

[[jpa.entity-persistence]]
== Persisting entities

[[jpa.entity-persistence.saving-entites]]
=== Saving entities

Saving an entity can be performed via the `CrudRepository.save(…)`-Method. It will persist or merge the given entity using the underlying JPA `EntityManager`. If the entity has not been persisted yet Spring Data JPA will save the entity via a call to the `entityManager.persist(…)` method, otherwise the `entityManager.merge(…)` method will be called.

==== Entity state detection strategies
Spring Data JPA offers the following strategies to detect whether an entity is new or not:

.Options for detection whether an entity is new in Spring Data JPA
[options = "autowidth"]
|===============
|Id-Property inspection (*default*)|By default Spring Data JPA inspects the identifier property of the given entity. If the identifier property is `null`, then the entity will be assumed as new, otherwise as not new.
|Implementing `Persistable`|If an entity implements `Persistable`, Spring Data JPA will delegate the new detection to the `isNew(…)` method of the entity. See the link:$$http://docs.spring.io/spring-data/data-commons/docs/current/api/index.html?org/springframework/data/domain/Persistable.html$$[JavaDoc] for details.
|Implementing `EntityInformation`|You can customize the `EntityInformation` abstraction used in the `SimpleJpaRepository` implementation by creating a subclass of `JpaRepositoryFactory` and overriding the `getEntityInformation(…)` method accordingly. You then have to register the custom implementation of `JpaRepositoryFactory` as a Spring bean. Note that this should be rarely necessary. See the link:$$http://docs.spring.io/spring-data/data-jpa/docs/current/api/index.html?org/springframework/data/jpa/repository/support/JpaRepositoryFactory.html$$[JavaDoc] for details.
|===============

[[jpa.query-methods]]
== Query methods

[[jpa.sample-app.finders.strategies]]
=== Query lookup strategies

The JPA module supports defining a query manually as String or have it being derived from the method name.

==== Declared queries
Although getting a query derived from the method name is quite convenient, one might face the situation in which either the method name parser does not support the keyword one wants to use or the method name would get unnecessarily ugly. So you can either use JPA named queries through a naming convention (see <<jpa.query-methods.named-queries>> for more information) or rather annotate your query method with `@Query` (see <<jpa.query-methods.at-query>> for details).

[[jpa.query-methods.query-creation]]
=== Query creation

Generally the query creation mechanism for JPA works as described in <<repositories.query-methods>>. Here's a short example of what a JPA query method translates into:

.Query creation from method names
====
----
public interface UserRepository extends Repository<User, Long> {

  List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
}
----
We will create a query using the JPA criteria API from this but essentially this translates into the following query: `select u from User u where u.emailAddress = ?1 and u.lastname = ?2`. Spring Data JPA will do a property check and traverse nested properties as described in <<repositories.query-methods.query-property-expressions>>. Here's an overview of the keywords supported for JPA and what a method containing that keyword essentially translates to.
====

.Supported keywords inside method names
[options = "header, autowidth"]
|===============
|Keyword|Sample|JPQL snippet
|`And`|`findByLastnameAndFirstname`|`… where x.lastname = ?1 and x.firstname = ?2`
|`Or`|`findByLastnameOrFirstname`|`… where x.lastname = ?1 or x.firstname = ?2`
|`Is,Equals`|`findByFirstname`,`findByFirstnameIs`,`findByFirstnameEquals`|`… where x.firstname = ?1`
|`Between`|`findByStartDateBetween`|`… where x.startDate between ?1 and ?2`
|`LessThan`|`findByAgeLessThan`|`… where x.age < ?1`
|`LessThanEqual`|`findByAgeLessThanEqual`|`… where x.age \<= ?1`
|`GreaterThan`|`findByAgeGreaterThan`|`… where x.age > ?1`
|`GreaterThanEqual`|`findByAgeGreaterThanEqual`|`… where x.age >= ?1`
|`After`|`findByStartDateAfter`|`… where x.startDate > ?1`
|`Before`|`findByStartDateBefore`|`… where x.startDate < ?1`
|`IsNull`|`findByAgeIsNull`|`… where x.age is null`
|`IsNotNull,NotNull`|`findByAge(Is)NotNull`|`… where x.age not null`
|`Like`|`findByFirstnameLike`|`… where x.firstname like ?1`
|`NotLike`|`findByFirstnameNotLike`|`… where x.firstname not like ?1`
|`StartingWith`|`findByFirstnameStartingWith`|`… where x.firstname like ?1` (parameter bound with appended `%`)
|`EndingWith`|`findByFirstnameEndingWith`|`… where x.firstname like ?1` (parameter bound with prepended `%`)
|`Containing`|`findByFirstnameContaining`|`… where x.firstname like ?1` (parameter bound wrapped in `%`)
|`OrderBy`|`findByAgeOrderByLastnameDesc`|`… where x.age = ?1 order by x.lastname desc`
|`Not`|`findByLastnameNot`|`… where x.lastname <> ?1`
|`In`|`findByAgeIn(Collection<Age> ages)`|`… where x.age in ?1`
|`NotIn`|`findByAgeNotIn(Collection<Age> age)`|`… where x.age not in ?1`
|`True`|`findByActiveTrue()`|`… where x.active = true`
|`False`|`findByActiveFalse()`|`… where x.active = false`
|`IgnoreCase`|`findByFirstnameIgnoreCase`|`… where UPPER(x.firstame) = UPPER(?1)`
|===============

[NOTE]
====
`In` and `NotIn` also take any subclass of `Collection` as parameter as well as arrays or varargs. For other syntactical versions of the very same logical operator check <<repository-query-keywords>>.
====

[[jpa.query-methods.named-queries]]
=== Using JPA NamedQueries

[NOTE]
====
The examples use simple `<named-query />` element and `@NamedQuery` annotation. The queries for these configuration elements have to be defined in JPA query language. Of course you can use `<named-native-query />` or `@NamedNativeQuery` too. These elements allow you to define the query in native SQL by losing the database platform independence.
====

==== XML named query definition
To use XML configuration simply add the necessary `<named-query />` element to the `orm.xml` JPA configuration file located in `META-INF` folder of your classpath. Automatic invocation of named queries is enabled by using some defined naming convention. For more details see below.

.XML named query configuration
====
[source, xml]
----
<named-query name="User.findByLastname">
  <query>select u from User u where u.lastname = ?1</query>
</named-query>
----
====

As you can see the query has a special name which will be used to resolve it at runtime.

==== Annotation configuration
Annotation configuration has the advantage of not needing another configuration file to be edited, probably lowering maintenance costs. You pay for that benefit by the need to recompile your domain class for every new query declaration.

.Annotation based named query configuration
====
[source, java]
----
@Entity
@NamedQuery(name = "User.findByEmailAddress",
  query = "select u from User u where u.emailAddress = ?1")
public class User {

}
----
====

==== Declaring interfaces
To allow execution of these named queries all you need to do is to specify the `UserRepository` as follows:

.Query method declaration in UserRepository
====
[source, java]
----
public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByLastname(String lastname);

  User findByEmailAddress(String emailAddress);
}
----
====

Spring Data will try to resolve a call to these methods to a named query, starting with the simple name of the configured domain class, followed by the method name separated by a dot. So the example here would use the named queries defined above instead of trying to create a query from the method name.

[[jpa.query-methods.at-query]]
=== Using @Query

Using named queries to declare queries for entities is a valid approach and works fine for a small number of queries. As the queries themselves are tied to the Java method that executes them you actually can bind them directly using the Spring Data JPA `@Query` annotation rather than annotating them to the domain class. This will free the domain class from persistence specific information and co-locate the query to the repository interface.

Queries annotated to the query method will take precedence over queries defined using `@NamedQuery` or named queries declared in `orm.xml`.

.Declare query at the query method using @Query
====
[source, java]
----
public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.emailAddress = ?1")
  User findByEmailAddress(String emailAddress);
}
----
====

==== Using advanced `LIKE` expressions

The query execution mechanism for manually defined queries using @Query allows the definition of advanced `LIKE` expressions inside the query definition.

.Advanced like-expressions in @Query
====
[source, java]
----
public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.firstname like %?1")
  List<User> findByFirstnameEndsWith(String firstname);
}
----
====

In the just shown sample `LIKE` delimiter character `%` is recognized and the query transformed into a valid JPQL query (removing the `%`). Upon query execution the parameter handed into the method call gets augmented with the previously recognized `LIKE` pattern.

==== Native queries

The `@Query` annotation allows to execute native queries by setting the `nativeQuery` flag to true.

.Declare a native query at the query method using @Query
====
[source, java]
----
public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
  User findByEmailAddress(String emailAddress);
}
----

====

Note, that we currently don't support execution of dynamic sorting for native queries as we'd have to manipulate the actual query declared and we cannot do this reliably for native SQL. You can however use native queries for pagination by specifying the count query yourself:

.Declare native count queries for pagination at the query method using @Query
====
[source, java]
----
public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
}
----

====

This also works with named native queries by adding the suffix `.count` to a copy of your query. Be aware that you probably must register a result set mapping for your count query, though.

[[jpa.named-parameters]]
=== Using named parameters

By default Spring Data JPA will use position based parameter binding as described in all the samples above. This makes query methods a little error prone to refactoring regarding the parameter position. To solve this issue you can use `@Param` annotation to give a method parameter a concrete name and bind the name in the query.

.Using named parameters
====
[source, java]
----
public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
  User findByLastnameOrFirstname(@Param("lastname") String lastname,
                                 @Param("firstname") String firstname);
}
----
====
Note that the method parameters are switched according to the occurrence in the query defined.

[NOTE]
====
Spring 4 fully supports Java 8’s parameter name discovery based on the `-parameters` compiler flag. Using this flag in your build as an alternative to debug information, you can omit the `@Param` annotation for named parameters.
====

[[jpa.query.spel-expressions]]
=== Using SpEL expressions

As of Spring Data JPA release 1.4 we support the usage of restricted SpEL template expressions in manually defined queries via `@Query`. Upon query execution these expressions are evaluated against a predefined set of variables. We support the following list of variables to be used in a manual query.

.Supported variables inside SpEL based query templates
[options="header, autowidth"]
|===============
|Variable|Usage|Description
|`entityName`|`select x from #{#entityName} x`|Inserts the `entityName` of the domain type associated with the given Repository. The `entityName` is resolved as follows: If the domain type has set the name property on the `@Entity` annotation then it will be used. Otherwise the simple class-name of the domain type will be used.
|===============

The following example demonstrates one use case for the `+#{#entityName}+` expression in a query string where you want to define a repository interface with a query method with a manually defined query. In order not to have to state the actual entity name in the query string of a `@Query` annotation one can use the `+#{#entityName}+` Variable.

[NOTE]
====
The `entityName` can be customized via the `@Entity` annotation. Customizations via `orm.xml` are not supported for the SpEL expressions.
====

.Using SpEL expressions in repository query methods - entityName
====
[source, java]
----
@Entity
public class User {

  @Id
  @GeneratedValue
  Long id;

  String lastname;
}

public interface UserRepository extends JpaRepository<User,Long> {

  @Query("select u from #{#entityName} u where u.lastname = ?1")
  List<User> findByLastname(String lastname);
}
----
====

Of course you could have just used User in the query declaration directly but that would require you to change the query as well. The reference to `#entityName` will pick up potential future remappings of the User class to a different entity name (e.g. by using `@Entity(name = "MyUser")`.

Another use case for the `#{#entityName}` expression in a query string is if you want to define a generic repository interface with specialized repository interfaces for a concrete domain type. In order not to have to repeat the definition of custom query methods on the concrete interfaces you can use the entity name expression in the query string of the `@Query` annotation in the generic repository interface.

.Using SpEL expressions in repository query methods - entityName with inheritance
====
[source, java]
----
@MappedSuperclass
public abstract class AbstractMappedType {
  …
  String attribute
}

@Entity
public class ConcreteType extends AbstractMappedType { … }

@NoRepositoryBean
public interface MappedTypeRepository<T extends AbstractMappedType>
  extends Repository<T, Long> {

  @Query("select t from #{#entityName} t where t.attribute = ?1")
  List<T> findAllByAttribute(String attribute);
}

public interface ConcreteRepository
  extends MappedTypeRepository<ConcreteType> { … }
----
====

In the example the interface `MappedTypeRepository` is the common parent interface for a few domain types extending `AbstractMappedType`. It also defines the generic method `findAllByAttribute(…)` which can be used on instances of the specialized repository interfaces. If you now invoke `findByAllAttribute(…)` on `ConcreteRepository` the query being executed will be `select t from ConcreteType t where t.attribute = ?1`.

[[jpa.modifying-queries]]
=== Modifying queries

All the sections above describe how to declare queries to access a given entity or collection of entities. Of course you can add custom modifying behaviour by using facilities described in <<repositories.custom-implementations>>. As this approach is feasible for comprehensive custom functionality, you can achieve the execution of modifying queries that actually only need parameter binding by annotating the query method with `@Modifying`:

.Declaring manipulating queries
====
[source, java]
----
@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);
----

====

This will trigger the query annotated to the method as updating query instead of a selecting one. As the `EntityManager` might contain outdated entities after the execution of the modifying query, we do not automatically clear it (see JavaDoc of `EntityManager.clear()` for details) since this will effectively drop all non-flushed changes still pending in the `EntityManager`. If you wish the `EntityManager` to be cleared automatically you can set `@Modifying` annotation's `clearAutomatically` attribute to `true`.

[[jpa.query-hints]]
=== Applying query hints
To apply JPA query hints to the queries declared in your repository interface you can use the `@QueryHints` annotation. It takes an array of JPA `@QueryHint` annotations plus a boolean flag to potentially disable the hints applied to the addtional count query triggered when applying pagination.

.Using QueryHints with a repository method
====
[source, java]
----
public interface UserRepository extends Repository<User, Long> {

  @QueryHints(value = { @QueryHint(name = "name", value = "value")},
              forCounting = false)
  Page<User> findByLastname(String lastname, Pageable pageable);
}
----
====
The just shown declaration would apply the configured `@QueryHint` for that actually query but omit applying it to the count query triggered to calculate the total number of pages.

[[jpa.entity-graph]]
=== Configuring Fetch- and LoadGraphs

The JPA 2.1 specification introduced support for specifiying Fetch- and LoadGraphs that we also support via the `@EntityGraph` annotation which allows to reference a `@NamedEntityGraph` definition, that can be annotated on an entity, to be used to configure the fetch plan of the resulting query. The type (Fetch / Load) of the fetching can be configured via the `type` attribute on the `@EntityGraph` annotation. Please have a look at the JPA 2.1 Spec 3.7.4 for further reference.

.Defining a named entity graph on an entity.
====
[source, java]
----
@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
  attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {

  // default fetch mode is lazy.
  @ManyToMany
  List<GroupMember> members = new ArrayList<GroupMember>();

  …
}
----
====

.Referencing a named entity graph definition on an repository query method.
====
[source, java]
----
@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
  GroupInfo getByGroupName(String name);

}
----
====

It is also possible to define _ad-hoc_ entity graphs via `@EntityGraph`. The provided `attributePaths` will be translated into the according `EntityGraph` without the need of having to explicitly add `@NamedEntityGraph` to your domain types.

.Using AD-HOC entity graph definition on an repository query method.
====
[source, java]
----
@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(attributePaths = { "members" })
  GroupInfo getByGroupName(String name);

}
----
====

include::{spring-data-commons-docs}/repository-projections.adoc[leveloffset=+2]

[[jpa.stored-procedures]]
== Stored procedures
The JPA 2.1 specification introduced support for calling stored procedures via the JPA criteria query API. We Introduced the `@Procedure` annotation for declaring stored procedure metadata on a repository method.

.The definition of the pus1inout procedure in HSQL DB.
====
[source, sql]
----
/;
DROP procedure IF EXISTS plus1inout
/;
CREATE procedure plus1inout (IN arg int, OUT res int)
BEGIN ATOMIC
 set res = arg + 1;
END
/;
----
====

Metadata for stored procedures can be configured via the `NamedStoredProcedureQuery` annotation on an entity type.

[[jpa.stored-procedure-entity-metadata]]
.StoredProcedure metadata definitions on an entity.
====
[source, java]
----
@Entity
@NamedStoredProcedureQuery(name = "User.plus1", procedureName = "plus1inout", parameters = {
  @StoredProcedureParameter(mode = ParameterMode.IN, name = "arg", type = Integer.class),
  @StoredProcedureParameter(mode = ParameterMode.OUT, name = "res", type = Integer.class) })
public class User {}
----
====

Stored procedures can be referenced from a repository method in multiple ways. The stored procedure to be called can either be defined directly via the `value` or `procedureName` attribute of the `@Procedure` annotation or indirectly via the `name` attribute. If no name is configured the name of the repository method is used as a fallback.

[[jpa.stored-procedure-reference]]
.Referencing explicitly mapped procedure with name "plus1inout" in database.
====
[source, java]
----
@Procedure("plus1inout")
Integer explicitlyNamedPlus1inout(Integer arg);
----
====

.Referencing implicitly mapped procedure with name "plus1inout" in database via `procedureName` alias.
====
[source, java]
----
@Procedure(procedureName = "plus1inout")
Integer plus1inout(Integer arg);
----
====

.Referencing explicitly mapped named stored procedure "User.plus1IO" in EntityManager.
====
[source, java]
----
@Procedure(name = "User.plus1IO")
Integer entityAnnotatedCustomNamedProcedurePlus1IO(@Param("arg") Integer arg);
----
====

.Referencing implicitly mapped named stored procedure "User.plus1" in EntityManager via method-name.
====
[source, java]
----
@Procedure
Integer plus1(@Param("arg") Integer arg);
----
====

[[specifications]]
== Specifications

JPA 2 introduces a criteria API that can be used to build queries programmatically. Writing a `criteria` you actually define the where-clause of a query for a domain class. Taking another step back these criteria can be regarded as predicate over the entity that is described by the JPA criteria API constraints.

Spring Data JPA takes the concept of a specification from Eric Evans' book "Domain Driven Design", following the same semantics and providing an API to define such specifications using the JPA criteria API. To support specifications you can extend your repository interface with the `JpaSpecificationExecutor` interface:

[source, java]
----
public interface CustomerRepository extends CrudRepository<Customer, Long>, JpaSpecificationExecutor {
 …
}
----

The additional interface carries methods that allow you to execute specifications in a variety of ways. For example, the `findAll` method will return all entities that match the specification:

[source, java]
----
List<T> findAll(Specification<T> spec);
----

The `Specification` interface is defined as follows:

[source, java]
----
public interface Specification<T> {
  Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
            CriteriaBuilder builder);
}
----

Okay, so what is the typical use case? Specifications can easily be used to build an extensible set of predicates on top of an entity that then can be combined and used with `JpaRepository` without the need to declare a query (method) for every needed combination. Here's an example:

.Specifications for a Customer
====
[source, java]
----
public class CustomerSpecs {

  public static Specification<Customer> isLongTermCustomer() {
    return new Specification<Customer>() {
      public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query,
            CriteriaBuilder builder) {

         LocalDate date = new LocalDate().minusYears(2);
         return builder.lessThan(root.get(_Customer.createdAt), date);
      }
    };
  }

  public static Specification<Customer> hasSalesOfMoreThan(MontaryAmount value) {
    return new Specification<Customer>() {
      public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
            CriteriaBuilder builder) {

         // build query here
      }
    };
  }
}
----
====

Admittedly the amount of boilerplate leaves room for improvement (that will hopefully be reduced by Java 8 closures) but the client side becomes much nicer as you will see below. The `_Customer` type is a metamodel type generated using the JPA Metamodel generator (see the link:$$http://docs.jboss.org/hibernate/jpamodelgen/1.0/reference/en-US/html_single/#whatisit$$[Hibernate implementation's documentation for example]). So the expression `_Customer.createdAt` is asuming the `Customer` having a `createdAt` attribute of type `Date`. Besides that we have expressed some criteria on a business requirement abstraction level and created executable `Specifications`. So a client might use a `Specification` as follows:

.Using a simple Specification
====
[source, java]
----
List<Customer> customers = customerRepository.findAll(isLongTermCustomer());
----
====

Okay, why not simply create a query for this kind of data access? You're right. Using a single `Specification` does not gain a lot of benefit over a plain query declaration. The power of specifications really shines when you combine them to create new `Specification` objects. You can achieve this through the `Specifications` helper class we provide to build expressions like this:

.Combined Specifications
====
[source, java]
----
MonetaryAmount amount = new MonetaryAmount(200.0, Currencies.DOLLAR);
List<Customer> customers = customerRepository.findAll(
  where(isLongTermCustomer()).or(hasSalesOfMoreThan(amount)));
----
As you can see, `Specifications` offers some glue-code methods to chain and combine `Specification` instances. Thus extending your data access layer is just a matter of creating new `Specification` implementations and combining them with ones already existing.
====

include::{spring-data-commons-docs}/query-by-example.adoc[leveloffset=+1]
include::query-by-example.adoc[leveloffset=+1]

[[transactions]]
== Transactionality
CRUD methods on repository instances are transactional by default. For reading operations the transaction configuration `readOnly` flag is set to true, all others are configured with a plain `@Transactional` so that default transaction configuration applies. For details see JavaDoc of `CrudRepository`. If you need to tweak transaction configuration for one of the methods declared in a repository simply redeclare the method in your repository interface as follows:

.Custom transaction configuration for CRUD
====
[source, java]
----
public interface UserRepository extends CrudRepository<User, Long> {

  @Override
  @Transactional(timeout = 10)
  public List<User> findAll();

  // Further query method declarations
}
----
This will cause the `findAll()` method to be executed with a timeout of 10 seconds and without the `readOnly` flag.
====

Another possibility to alter transactional behaviour is using a facade or service implementation that typically covers more than one repository. Its purpose is to define transactional boundaries for non-CRUD operations:

.Using a facade to define transactions for multiple repository calls
====
[source, java]
----
@Service
class UserManagementImpl implements UserManagement {

  private final UserRepository userRepository;
  private final RoleRepository roleRepository;

  @Autowired
  public UserManagementImpl(UserRepository userRepository,
    RoleRepository roleRepository) {
    this.userRepository = userRepository;
    this.roleRepository = roleRepository;
  }

  @Transactional
  public void addRoleToAllUsers(String roleName) {

    Role role = roleRepository.findByName(roleName);

    for (User user : userRepository.findAll()) {
      user.addRole(role);
      userRepository.save(user);
    }
}
----
This will cause call to `addRoleToAllUsers(…)` to run inside a transaction (participating in an existing one or create a new one if none already running). The transaction configuration at the repositories will be neglected then as the outer transaction configuration determines the actual one used. Note that you will have to activate `<tx:annotation-driven />` or use `@EnableTransactionManagement` explicitly to get annotation based configuration at facades working. The example above assumes you are using component scanning.
====

[[transactional-query-methods]]
=== Transactional query methods
To allow your query methods to be transactional simply use `@Transactional` at the repository interface you define.

.Using @Transactional at query methods
====
[source, java]
----
@Transactional(readOnly = true)
public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByLastname(String lastname);

  @Modifying
  @Transactional
  @Query("delete from User u where u.active = false")
  void deleteInactiveUsers();
}
----
Typically you will want the readOnly flag set to true as most of the query methods will only read data. In contrast to that `deleteInactiveUsers()` makes use of the `@Modifying` annotation and overrides the transaction configuration. Thus the method will be executed with `readOnly` flag set to `false`.
====

[NOTE]
====
It's definitely reasonable to use transactions for read only queries and we can mark them as such by setting the `readOnly` flag. This will not, however, act as check that you do not trigger a manipulating query (although some databases reject `INSERT` and `UPDATE` statements inside a read only transaction). The `readOnly` flag instead is propagated as hint to the underlying JDBC driver for performance optimizations. Furthermore, Spring will perform some optimizations on the underlying JPA provider. E.g. when used with Hibernate the flush mode is set to `NEVER` when you configure a transaction as `readOnly` which causes Hibernate to skip dirty checks (a noticeable improvement on large object trees).
====

[[locking]]
== Locking
To specify the lock mode to be used the `@Lock` annotation can be used on query methods:

.Defining lock metadata on query methods
====
[source, java]
----
interface UserRepository extends Repository<User, Long> {

  // Plain query method
  @Lock(LockModeType.READ)
  List<User> findByLastname(String lastname);
}
----
====

This method declaration will cause the query being triggered to be equipped with the `LockModeType` `READ`. You can also define locking for CRUD methods by redeclaring them in your repository interface and adding the `@Lock` annotation:

.Defining lock metadata on CRUD methods
====
[source, java]
----
interface UserRepository extends Repository<User, Long> {

  // Redeclaration of a CRUD method
  @Lock(LockModeType.READ);
  List<User> findAll();
}
----
====

:leveloffset: +1
include::{spring-data-commons-docs}/auditing.adoc[]
:leveloffset: -1

[[jpa.auditing]]
== JPA Auditing

[[jpa.auditing.configuration]]
=== General auditing configuration

Spring Data JPA ships with an entity listener that can be used to trigger capturing auditing information. So first you have to register the `AuditingEntityListener` inside your `orm.xml` to be used for all entities in your persistence contexts:

.Auditing configuration orm.xml
====
[source, xml]
----
<persistence-unit-metadata>
  <persistence-unit-defaults>
    <entity-listeners>
      <entity-listener class="….data.jpa.domain.support.AuditingEntityListener" />
    </entity-listeners>
  </persistence-unit-defaults>
</persistence-unit-metadata>
----
====

You can also enable the `AuditingEntityListener` per entity using the `@EntityListeners` annotation:

====
[source, java]
----
@Entity
@EntityListeners(AuditingEntityListener.class)
public class MyEntity {

}
----
====

Note that the auditing feature requires `spring-aspects.jar` to be on the classpath.

With that in place, activating auditing functionality is just a matter of adding the Spring Data JPA `auditing` namespace element to your configuration:

.Activating auditing using XML configuration
====
[source, xml]
----
<jpa:auditing auditor-aware-ref="yourAuditorAwareBean" />
----
====

As of Spring Data JPA 1.5, auditing can be enabled by annotating a configuration class with the @EnableJpaAuditing annotation.

.Activating auditing via Java configuration
====
[source, java]
----
@Configuration
@EnableJpaAuditing
class Config {

  @Bean
  public AuditorAware<AuditableUser> auditorProvider() {
    return new AuditorAwareImpl();
  }
}
----
====

If you expose a bean of type `AuditorAware` to the `ApplicationContext`, the auditing infrastructure will pick it up automatically and use it to determine the current user to be set on domain types. If you have multiple implementations registered in the `ApplicationContext`, you can select the one to be used by explicitly setting the `auditorAwareRef` attribute of `@EnableJpaAuditing`.

[[jpa.misc]]
= Miscellaneous

[[jpa.misc.jpa-context]]
== Using JpaContext in custom implementations

When working with multiple `EntityManager` instances and <<repositories.custom-implementations,custom repository implementations>> you'll need to make sure you wire the correct `EntityManager` into the repository implementation class. This could be solved by explicitly naming the `EntityManager` in the `@PersistenceContext` annotation or using `@Qualifier` in case the `EntityManager` is injected via `@Autowired`.

As of Spring Data JPA 1.9, we ship a class `JpaContext` that allows to obtain the `EntityManager` by managed domain class assuming it's only managed by one of the `EntityManager` instances in the application.

.Using JpaContext in a custom repository implementation
====
[source, java]
----
class UserRepositoryImpl implements UserRepositoryCustom {

  private final EntityManager em;

  @Autowired
  public UserRepositoryImpl(JpaContext context) {
    this.em = context.getEntityManagerByManagedType(User.class);
  }

  …
}
----
====

This approach has the advantage that the repository does not have to be touched to alter the reference to the persistence unit in case the domain type gets assigned to a different persistence unit.

[[jpa.misc.merging-persistence-units]]
== Merging persistence units

Spring supports having multiple persistence units out of the box. Sometimes, however, you might want to modularize your application but still make sure that all these modules run inside a single persistence unit at runtime. To do so Spring Data JPA offers a `PersistenceUnitManager` implementation that automatically merges persistence units based on their name.

.Using MergingPersistenceUnitmanager
====
[source, xml]
----
<bean class="….LocalContainerEntityManagerFactoryBean">
  <property name="persistenceUnitManager">
    <bean class="….MergingPersistenceUnitManager" />
  </property>
</bean>
----
====

[[jpa.misc.entity-scanning]]
=== Classpath scanning for @Entity classes and JPA mapping files

A plain JPA setup requires all annotation mapped entity classes listed in `orm.xml`. Same applies to XML mapping files. Spring Data JPA provides a ClasspathScanningPersistenceUnitPostProcessor that gets a base package configured and optionally takes a mapping filename pattern. It will then scan the given package for classes annotated with @Entity or @MappedSuperclass and also loads the configuration files matching the filename pattern and hands them to the JPA configuration. The PostProcessor has to be configured like this:

.Using ClasspathScanningPersistenceUnitPostProcessor
====
[source, xml]
----
<bean class="….LocalContainerEntityManagerFactoryBean">
  <property name="persistenceUnitPostProcessors">
    <list>
      <bean class="org.springframework.data.jpa.support.ClasspathScanningPersistenceUnitPostProcessor">
        <constructor-arg value="com.acme.domain" />
        <property name="mappingFileNamePattern" value="**/*Mapping.xml" />
      </bean>
    </list>
  </property>
</bean>
----
====

[NOTE]
====
As of Spring 3.1 a package to scan can be configured on the LocalContainerEntityManagerFactoryBean directly to enable classpath scanning for entity classes. See the link:$$http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html#setPackagesToScan(java.lang.String...)$$[JavaDoc] for details.
====

[[jpd.misc.cdi-integration]]
== CDI integration

Instances of the repository interfaces are usually created by a container, which Spring is the most natural choice when working with Spring Data. There's sophisticated support to easily set up Spring to create bean instances documented in <<repositories.create-instances>>. As of version 1.1.0 Spring Data JPA ships with a custom CDI extension that allows using the repository abstraction in CDI environments. The extension is part of the JAR so all you need to do to activate it is dropping the Spring Data JPA JAR into your classpath.

You can now set up the infrastructure by implementing a CDI Producer for the `EntityManagerFactory` and `EntityManager`:

[source, java]
----
class EntityManagerFactoryProducer {

  @Produces
  @ApplicationScoped
  public EntityManagerFactory createEntityManagerFactory() {
    return Persistence.createEntityManagerFactory("my-presistence-unit");
  }

  public void close(@Disposes EntityManagerFactory entityManagerFactory) {
    entityManagerFactory.close();
  }

  @Produces
  @RequestScoped
  public EntityManager createEntityManager(EntityManagerFactory entityManagerFactory) {
    return entityManagerFactory.createEntityManager();
  }

  public void close(@Disposes EntityManager entityManager) {
    entityManager.close();
  }
}
----

The necessary setup can vary depending on the JavaEE environment you run in. It might also just be enough to redeclare a `EntityManager` as CDI bean as follows:

[source, java]
----
class CdiConfig {

  @Produces
  @RequestScoped
  @PersistenceContext
  public EntityManager entityManager;
}
----

In this example, the container has to be capable of creating JPA `EntityManagers` itself. All the configuration does is re-exporting the JPA `EntityManager` as CDI bean.

The Spring Data JPA CDI extension will pick up all EntityManagers availables as CDI beans and create a proxy for a Spring Data repository whenever an bean of a repository type is requested by the container. Thus obtaining an instance of a Spring Data repository is a matter of declaring an `@Injected` property:

[source, java]
----
class RepositoryClient {

  @Inject
  PersonRepository repository;

  public void businessMethod() {
    List<Person> people = repository.findAll();
  }
}
----

## 内容2
### 文件路径：
src/main/java/org/springframework/data/jpa/domain/JpaSort.java
### 代码内容：
package org.springframework.data.jpa.domain;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.persistence.metamodel.Attribute;
import javax.persistence.metamodel.PluralAttribute;

import org.springframework.data.domain.Sort;
import org.springframework.util.Assert;

/**
 * Sort option for queries that wraps JPA meta-model {@link Attribute}s for sorting.
 *
 * @author Thomas Darimont
 * @author Oliver Gierke
 */
public class JpaSort extends Sort {

	private static final long serialVersionUID = 1L;

	/**
	 * Creates a new {@link JpaSort} for the given attributes with the default sort direction.
	 *
	 * @param attributes must not be {@literal null} or empty.
	 */
	public JpaSort(Attribute<?, ?>... attributes) {
		this(DEFAULT_DIRECTION, attributes);
	}

	/**
	 * Creates a new {@link JpaSort} instance with the given {@link Path}s.
	 *
	 * @param paths must not be {@literal null} or empty.
	 */
	public JpaSort(JpaSort.Path<?, ?>... paths) {
		this(DEFAULT_DIRECTION, paths);
	}

	/**
	 * Creates a new {@link JpaSort} for the given direction and attributes.
	 *
	 * @param direction the sorting direction.
	 * @param attributes must not be {@literal null} or empty.
	 */
	public JpaSort(Direction direction, Attribute<?, ?>... attributes) {
		this(direction, paths(attributes));
	}

	/**
	 * Creates a new {@link JpaSort} for the given direction and {@link Path}s.
	 *
	 * @param direction the sorting direction.
	 * @param paths must not be {@literal null} or empty.
	 */
	public JpaSort(Direction direction, Path<?, ?>... paths) {
		this(direction, Arrays.asList(paths));
	}

	private JpaSort(Direction direction, List<Path<?, ?>> paths) {
		this(Collections.<Order> emptyList(), direction, paths);
	}

	private JpaSort(List<Order> orders, Direction direction, List<Path<?, ?>> paths) {
		super(combine(orders, direction, paths));
	}

	/**
	 * Returns a new {@link JpaSort} with the given sorting criteria added to the current one.
	 *
	 * @param direction can be {@literal null}.
	 * @param attributes must not be {@literal null}.
	 * @return
	 */
	public JpaSort and(Direction direction, Attribute<?, ?>... attributes) {

		Assert.notNull(attributes, "Attributes must not be null!");

		return and(direction, paths(attributes));
	}

	/**
	 * Returns a new {@link JpaSort} with the given sorting criteria added to the current one.
	 *
	 * @param direction can be {@literal null}.
	 * @param paths must not be {@literal null}.
	 * @return
	 */
	public JpaSort and(Direction direction, Path<?, ?>... paths) {

		Assert.notNull(paths, "Paths must not be null!");

		List<Order> existing = new ArrayList<Order>();

		for (Order order : this) {
			existing.add(order);
		}

		return new JpaSort(existing, direction, Arrays.asList(paths));
	}

	/**
	 * Turns the given {@link Attribute}s into {@link Path}s.
	 *
	 * @param attributes must not be {@literal null} or empty.
	 * @return
	 */
	private static Path<?, ?>[] paths(Attribute<?, ?>[] attributes) {

		Assert.notNull(attributes, "Attributes must not be null!");
		Assert.isTrue(attributes.length > 0, "Attributes must not be empty");

		Path<?, ?>[] paths = new Path[attributes.length];

		for (int i = 0; i < attributes.length; i++) {
			paths[i] = path(attributes[i]);
		}

		return paths;
	}

	private static List<Order> combine(List<Order> orders, Direction direction, List<Path<?, ?>> paths) {

		List<Order> result = new ArrayList<Sort.Order>(orders);

		for (Path<?, ?> path : paths) {
			result.add(new Order(direction, path.toString()));
		}

		return result;
	}

	/**
	 * Creates a new {@link Path} for the given {@link Attribute}.
	 *
	 * @param attribute must not be {@literal null}.
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <A extends Attribute<T, S>, T, S> Path<T, S> path(A attribute) {

		Assert.notNull(attribute, "Attribute must not be null!");
		return new Path<T, S>(Arrays.asList(attribute));
	}

	/**
	 * Creates a new {@link Path} for the given {@link PluralAttribute}.
	 *
	 * @param attribute must not be {@literal null}.
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <P extends PluralAttribute<T, ?, S>, T, S> Path<T, S> path(P attribute) {

		Assert.notNull(attribute, "Attribute must not be null!");
		return new Path<T, S>(Arrays.asList(attribute));
	}

	/**
	 * Value object to abstract a collection of {@link Attribute}s.
	 *
	 * @author Oliver Gierke
	 */
	public static class Path<T, S> {

		private final Collection<Attribute<?, ?>> attributes;

		private Path(List<? extends Attribute<?, ?>> attributes) {
			this.attributes = Collections.unmodifiableList(attributes);
		}

		/**
		 * Collects the given {@link Attribute} and returning a new {@link Path} pointing to the attribute type.
		 *
		 * @param attribute must not be {@literal null}.
		 * @return
		 */
		public <A extends Attribute<S, U>, U> Path<S, U> dot(A attribute) {
			return new Path<S, U>(add(attribute));
		}

		/**
		 * Collects the given {@link PluralAttribute} and returning a new {@link Path} pointing to the attribute type.
		 *
		 * @param attribute must not be {@literal null}.
		 * @return
		 */
		public <P extends PluralAttribute<S, ?, U>, U> Path<S, U> dot(P attribute) {
			return new Path<S, U>(add(attribute));
		}

		private List<Attribute<?, ?>> add(Attribute<?, ?> attribute) {

			Assert.notNull(attribute, "Attribute must not be null!");

			List<Attribute<?, ?>> newAttributes = new ArrayList<Attribute<?, ?>>(attributes.size() + 1);
			newAttributes.addAll(attributes);
			newAttributes.add(attribute);
			return newAttributes;
		}

		/*
		 * (non-Javadoc)
		 * @see java.lang.Object#toString()
		 */
		@Override
		public String toString() {

			StringBuilder builder = new StringBuilder();

			for (Attribute<?, ?> attribute : attributes) {
				builder.append(attribute.getName()).append(".");
			}

			return builder.length() == 0 ? "" : builder.substring(0, builder.lastIndexOf("."));
		}
	}
}

## 内容3
### 文件路径：
src/main/java/org/springframework/data/jpa/repository/query/QueryUtils.java
### 代码内容：
package org.springframework.data.jpa.repository.query;

import static java.util.regex.Pattern.*;
import static javax.persistence.metamodel.Attribute.PersistentAttributeType.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.persistence.EntityManager;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Parameter;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Fetch;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.Attribute;
import javax.persistence.metamodel.Attribute.PersistentAttributeType;
import javax.persistence.metamodel.Bindable;
import javax.persistence.metamodel.ManagedType;
import javax.persistence.metamodel.PluralAttribute;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mapping.PropertyPath;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * Simple utility class to create JPA queries.
 *
 * @author Oliver Gierke
 * @author Kevin Raymond
 * @author Thomas Darimont
 * @author Komi Innocent
 */
public abstract class QueryUtils {

	public static final String COUNT_QUERY_STRING = "select count(%s) from %s x";
	public static final String DELETE_ALL_QUERY_STRING = "delete from %s x";

	private static final String DEFAULT_ALIAS = "x";
	private static final String COUNT_REPLACEMENT_TEMPLATE = "select count(%s) $5$6$7";
	private static final String SIMPLE_COUNT_VALUE = "$2";
	private static final String COMPLEX_COUNT_VALUE = "$3$6";
	private static final String ORDER_BY_PART = "(?iu)\\s+order\\s+by\\s+.*$";

	private static final Pattern ALIAS_MATCH;
	private static final Pattern COUNT_MATCH;
	private static final Pattern PROJECTION_CLAUSE = Pattern.compile("select\\s+(.+)\\s+from");

	private static final Pattern NO_DIGITS = Pattern.compile("\\D+");
	private static final String IDENTIFIER = "[\\p{Lu}\\P{InBASIC_LATIN}\\p{Alnum}._$]+";
	private static final String IDENTIFIER_GROUP = String.format("(%s)", IDENTIFIER);

	private static final String JOIN = "join\\s" + IDENTIFIER + "\\s(as\\s)?" + IDENTIFIER_GROUP;
	private static final Pattern JOIN_PATTERN = Pattern.compile(JOIN, Pattern.CASE_INSENSITIVE);

	private static final String EQUALS_CONDITION_STRING = "%s.%s = :%s";
	private static final Pattern ORDER_BY = Pattern.compile(".*order\\s+by\\s+.*", CASE_INSENSITIVE);

	private static final Pattern NAMED_PARAMETER = Pattern.compile(":" + IDENTIFIER + "|\\#" + IDENTIFIER,
			CASE_INSENSITIVE);

	private static final Pattern CONSTRUCTOR_EXPRESSION;

	private static final Map<PersistentAttributeType, Class<? extends Annotation>> ASSOCIATION_TYPES;

	private static final int QUERY_JOIN_ALIAS_GROUP_INDEX = 2;
	private static final int VARIABLE_NAME_GROUP_INDEX = 4;

	static {

		StringBuilder builder = new StringBuilder();
		builder.append("(?<=from)"); // from as starting delimiter
		builder.append("(?:\\s)+"); // at least one space separating
		builder.append(IDENTIFIER_GROUP); // Entity name, can be qualified (any
		builder.append("(?:\\sas)*"); // exclude possible "as" keyword
		builder.append("(?:\\s)+"); // at least one space separating
		builder.append("(?!(?:where))(\\w*)"); // the actual alias

		ALIAS_MATCH = compile(builder.toString(), CASE_INSENSITIVE);

		builder = new StringBuilder();
		builder.append("(select\\s+((distinct )?(.+?)?)\\s+)?(from\\s+");
		builder.append(IDENTIFIER);
		builder.append("(?:\\s+as)?\\s+)");
		builder.append(IDENTIFIER_GROUP);
		builder.append("(.*)");

		COUNT_MATCH = compile(builder.toString(), CASE_INSENSITIVE);

		Map<PersistentAttributeType, Class<? extends Annotation>> persistentAttributeTypes = new HashMap<PersistentAttributeType, Class<? extends Annotation>>();
		persistentAttributeTypes.put(ONE_TO_ONE, OneToOne.class);
		persistentAttributeTypes.put(ONE_TO_MANY, null);
		persistentAttributeTypes.put(MANY_TO_ONE, ManyToOne.class);
		persistentAttributeTypes.put(MANY_TO_MANY, null);
		persistentAttributeTypes.put(ELEMENT_COLLECTION, null);

		ASSOCIATION_TYPES = Collections.unmodifiableMap(persistentAttributeTypes);

		builder = new StringBuilder();
		builder.append("select");
		builder.append("\\s+"); // at least one space separating
		builder.append("(.*\\s+)?"); // anything in between (e.g. distinct) at least one space separating
		builder.append("new");
		builder.append("\\s+"); // at least one space separating
		builder.append(IDENTIFIER);
		builder.append("\\s*"); // zero to unlimited space separating
		builder.append("\\(");
		builder.append(".*");
		builder.append("\\)");

		CONSTRUCTOR_EXPRESSION = compile(builder.toString(), CASE_INSENSITIVE + DOTALL);
	}

	/**
	 * Private constructor to prevent instantiation.
	 */
	private QueryUtils() {

	}

	/**
	 * Returns the query string to execute an exists query for the given id attributes.
	 *
	 * @param entityName the name of the entity to create the query for, must not be {@literal null}.
	 * @param countQueryPlaceHolder the placeholder for the count clause, must not be {@literal null}.
	 * @param idAttributes the id attributes for the entity, must not be {@literal null}.
	 * @return
	 */
	public static String getExistsQueryString(String entityName, String countQueryPlaceHolder,
			Iterable<String> idAttributes) {

		StringBuilder sb = new StringBuilder(String.format(COUNT_QUERY_STRING, countQueryPlaceHolder, entityName));
		sb.append(" WHERE ");

		for (String idAttribute : idAttributes) {
			sb.append(String.format(EQUALS_CONDITION_STRING, "x", idAttribute, idAttribute));
			sb.append(" AND ");
		}

		sb.append("1 = 1");
		return sb.toString();
	}

	/**
	 * Returns the query string for the given class name.
	 *
	 * @param template
	 * @param entityName
	 * @return
	 */
	public static String getQueryString(String template, String entityName) {

		Assert.hasText(entityName, "Entity name must not be null or empty!");

		return String.format(template, entityName);
	}

	/**
	 * Adds {@literal order by} clause to the JPQL query. Uses the {@link #DEFAULT_ALIAS} to bind the sorting property to.
	 *
	 * @param query
	 * @param sort
	 * @return
	 */
	public static String applySorting(String query, Sort sort) {
		return applySorting(query, sort, detectAlias(query));
	}

	/**
	 * Adds {@literal order by} clause to the JPQL query.
	 *
	 * @param query
	 * @param sort
	 * @param alias
	 * @return
	 */
	public static String applySorting(String query, Sort sort, String alias) {

		Assert.hasText(query);

		if (null == sort || !sort.iterator().hasNext()) {
			return query;
		}

		StringBuilder builder = new StringBuilder(query);

		if (!ORDER_BY.matcher(query).matches()) {
			builder.append(" order by ");
		} else {
			builder.append(", ");
		}

		Set<String> aliases = getOuterJoinAliases(query);

		for (Order order : sort) {
			builder.append(getOrderClause(aliases, alias, order)).append(", ");
		}

		builder.delete(builder.length() - 2, builder.length());

		return builder.toString();
	}

	/**
	 * Returns the order clause for the given {@link Order}. Will prefix the clause with the given alias if the referenced
	 * property refers to a join alias, i.e. starts with {@code $alias.}.
	 *
	 * @param joinAliases the join aliases of the original query.
	 * @param alias the alias for the root entity.
	 * @param order the order object to build the clause for.
	 * @return
	 */
	private static String getOrderClause(Set<String> joinAliases, String alias, Order order) {

		String property = order.getProperty();
		boolean qualifyReference = !property.contains("("); // ( indicates a function

		for (String joinAlias : joinAliases) {
			if (property.startsWith(joinAlias.concat("."))) {
				qualifyReference = false;
				break;
			}
		}

		String reference = qualifyReference && StringUtils.hasText(alias) ? String.format("%s.%s", alias, property)
				: property;
		String wrapped = order.isIgnoreCase() ? String.format("lower(%s)", reference) : reference;

		return String.format("%s %s", wrapped, toJpaDirection(order));
	}

	/**
	 * Returns the aliases used for {@code left (outer) join}s.
	 *
	 * @param query
	 * @return
	 */
	static Set<String> getOuterJoinAliases(String query) {

		Set<String> result = new HashSet<String>();
		Matcher matcher = JOIN_PATTERN.matcher(query);

		while (matcher.find()) {

			String alias = matcher.group(QUERY_JOIN_ALIAS_GROUP_INDEX);
			if (StringUtils.hasText(alias)) {
				result.add(alias);
			}
		}

		return result;
	}

	private static String toJpaDirection(Order order) {
		return order.getDirection().name().toLowerCase(Locale.US);
	}

	/**
	 * Resolves the alias for the entity to be retrieved from the given JPA query.
	 *
	 * @param query
	 * @return
	 */
	public static String detectAlias(String query) {

		Matcher matcher = ALIAS_MATCH.matcher(query);

		return matcher.find() ? matcher.group(2) : null;
	}

	/**
	 * Creates a where-clause referencing the given entities and appends it to the given query string. Binds the given
	 * entities to the query.
	 *
	 * @param <T>
	 * @param queryString
	 * @param entities
	 * @param entityManager
	 * @return
	 */
	public static <T> Query applyAndBind(String queryString, Iterable<T> entities, EntityManager entityManager) {

		Assert.notNull(queryString);
		Assert.notNull(entities);
		Assert.notNull(entityManager);

		Iterator<T> iterator = entities.iterator();

		if (!iterator.hasNext()) {
			return entityManager.createQuery(queryString);
		}

		String alias = detectAlias(queryString);
		StringBuilder builder = new StringBuilder(queryString);
		builder.append(" where");

		int i = 0;

		while (iterator.hasNext()) {

			iterator.next();

			builder.append(String.format(" %s = ?%d", alias, ++i));

			if (iterator.hasNext()) {
				builder.append(" or");
			}
		}

		Query query = entityManager.createQuery(builder.toString());

		iterator = entities.iterator();
		i = 0;

		while (iterator.hasNext()) {
			query.setParameter(++i, iterator.next());
		}

		return query;
	}

	/**
	 * Creates a count projected query from the given original query.
	 *
	 * @param originalQuery must not be {@literal null} or empty.
	 * @return
	 */
	public static String createCountQueryFor(String originalQuery) {
		return createCountQueryFor(originalQuery, null);
	}

	/**
	 * Creates a count projected query from the given original query.
	 *
	 * @param originalQuery must not be {@literal null}.
	 * @param countProjection may be {@literal null}.
	 * @return
	 * @since 1.6
	 */
	public static String createCountQueryFor(String originalQuery, String countProjection) {

		Assert.hasText(originalQuery, "OriginalQuery must not be null or empty!");

		Matcher matcher = COUNT_MATCH.matcher(originalQuery);
		String countQuery = null;

		if (countProjection == null) {

			String variable = matcher.matches() ? matcher.group(VARIABLE_NAME_GROUP_INDEX) : null;
			boolean useVariable = variable != null && StringUtils.hasText(variable) && !variable.startsWith("new")
					&& !variable.startsWith("count(") && !variable.contains(",");

			String replacement = useVariable ? SIMPLE_COUNT_VALUE : COMPLEX_COUNT_VALUE;
			countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, replacement));
		} else {
			countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, countProjection));
		}

		return countQuery.replaceFirst(ORDER_BY_PART, "");
	}

	/**
	 * Returns whether the given {@link Query} contains named parameters.
	 *
	 * @param query
	 * @return
	 */
	public static boolean hasNamedParameter(Query query) {

		for (Parameter<?> parameter : query.getParameters()) {

			String name = parameter.getName();

			// Hibernate 3 specific hack as it returns the index as String for the name.
			if (name != null && NO_DIGITS.matcher(name).find()) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Returns whether the given query contains named parameters.
	 *
	 * @param query can be {@literal null} or empty.
	 * @return
	 */
	public static boolean hasNamedParameter(String query) {
		return StringUtils.hasText(query) && NAMED_PARAMETER.matcher(query).find();
	}

	/**
	 * Turns the given {@link Sort} into {@link javax.persistence.criteria.Order}s.
	 *
	 * @param sort the {@link Sort} instance to be transformed into JPA {@link javax.persistence.criteria.Order}s.
	 * @param root must not be {@literal null}.
	 * @param cb must not be {@literal null}.
	 * @return
	 */
	public static List<javax.persistence.criteria.Order> toOrders(Sort sort, Root<?> root, CriteriaBuilder cb) {

		List<javax.persistence.criteria.Order> orders = new ArrayList<javax.persistence.criteria.Order>();

		if (sort == null) {
			return orders;
		}

		Assert.notNull(root);
		Assert.notNull(cb);

		for (org.springframework.data.domain.Sort.Order order : sort) {
			orders.add(toJpaOrder(order, root, cb));
		}

		return orders;
	}

	/**
	 * Returns whether the given JPQL query contains a constructor expression.
	 *
	 * @param query must not be {@literal null} or empty.
	 * @return
	 * @since 1.10
	 */
	public static boolean hasConstructorExpression(String query) {

		Assert.hasText(query, "Query must not be null or empty!");

		return CONSTRUCTOR_EXPRESSION.matcher(query).find();
	}

	/**
	 * Returns the projection part of the query, i.e. everything between {@code select} and {@code from}.
	 *
	 * @param query must not be {@literal null} or empty.
	 * @return
	 * @since 1.10.2
	 */
	public static String getProjection(String query) {

		Assert.hasText(query, "Query must not be null or empty!");

		Matcher matcher = PROJECTION_CLAUSE.matcher(query);
		return matcher.find() ? matcher.group(1) : "";
	}

	/**
	 * Creates a criteria API {@link javax.persistence.criteria.Order} from the given {@link Order}.
	 *
	 * @param order the order to transform into a JPA {@link javax.persistence.criteria.Order}
	 * @param root the {@link Root} the {@link Order} expression is based on
	 * @param cb the {@link CriteriaBuilder} to build the {@link javax.persistence.criteria.Order} with
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static javax.persistence.criteria.Order toJpaOrder(Order order, Root<?> root, CriteriaBuilder cb) {

		PropertyPath property = PropertyPath.from(order.getProperty(), root.getJavaType());
		Expression<?> expression = toExpressionRecursively(root, property);

		if (order.isIgnoreCase() && String.class.equals(expression.getJavaType())) {
			Expression<String> lower = cb.lower((Expression<String>) expression);
			return order.isAscending() ? cb.asc(lower) : cb.desc(lower);
		} else {
			return order.isAscending() ? cb.asc(expression) : cb.desc(expression);
		}
	}

	@SuppressWarnings("unchecked")
	static <T> Expression<T> toExpressionRecursively(From<?, ?> from, PropertyPath property) {

		Bindable<?> propertyPathModel = null;
		Bindable<?> model = from.getModel();
		String segment = property.getSegment();

		if (model instanceof ManagedType) {

			/*
			 *  Required to keep support for EclipseLink 2.4.x. TODO: Remove once we drop that (probably Dijkstra M1)
			 *  See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=413892
			 */
			propertyPathModel = (Bindable<?>) ((ManagedType<?>) model).getAttribute(segment);
		} else {
			propertyPathModel = from.get(segment).getModel();
		}

		if (requiresJoin(propertyPathModel, model instanceof PluralAttribute) && !isAlreadyFetched(from, segment)) {
			Join<?, ?> join = getOrCreateJoin(from, segment);
			return (Expression<T>) (property.hasNext() ? toExpressionRecursively(join, property.next()) : join);
		} else {
			Path<Object> path = from.get(segment);
			return (Expression<T>) (property.hasNext() ? toExpressionRecursively(path, property.next()) : path);
		}
	}

	/**
	 * Returns whether the given {@code propertyPathModel} requires the creation of a join. This is the case if we find a
	 * non-optional association.
	 *
	 * @param propertyPathModel must not be {@literal null}.
	 * @param for
	 * @return
	 */
	private static boolean requiresJoin(Bindable<?> propertyPathModel, boolean forPluralAttribute) {

		if (propertyPathModel == null && forPluralAttribute) {
			return true;
		}

		if (!(propertyPathModel instanceof Attribute)) {
			return false;
		}

		Attribute<?, ?> attribute = (Attribute<?, ?>) propertyPathModel;

		if (!ASSOCIATION_TYPES.containsKey(attribute.getPersistentAttributeType())) {
			return false;
		}

		Class<? extends Annotation> associationAnnotation = ASSOCIATION_TYPES.get(attribute.getPersistentAttributeType());

		if (associationAnnotation == null) {
			return true;
		}

		Member member = attribute.getJavaMember();

		if (!(member instanceof AnnotatedElement)) {
			return true;
		}

		Annotation annotation = AnnotationUtils.getAnnotation((AnnotatedElement) member, associationAnnotation);
		return annotation == null ? true : (Boolean) AnnotationUtils.getValue(annotation, "optional");
	}

	static Expression<Object> toExpressionRecursively(Path<Object> path, PropertyPath property) {

		Path<Object> result = path.get(property.getSegment());
		return property.hasNext() ? toExpressionRecursively(result, property.next()) : result;
	}

	/**
	 * Returns an existing join for the given attribute if one already exists or creates a new one if not.
	 *
	 * @param from the {@link From} to get the current joins from.
	 * @param attribute the {@link Attribute} to look for in the current joins.
	 * @return will never be {@literal null}.
	 */
	private static Join<?, ?> getOrCreateJoin(From<?, ?> from, String attribute) {

		for (Join<?, ?> join : from.getJoins()) {

			boolean sameName = join.getAttribute().getName().equals(attribute);

			if (sameName && join.getJoinType().equals(JoinType.LEFT)) {
				return join;
			}
		}

		return from.join(attribute, JoinType.LEFT);
	}

	/**
	 * Return whether the given {@link From} contains a fetch declaration for the attribute with the given name.
	 *
	 * @param from the {@link From} to check for fetches.
	 * @param attribute the attribute name to check.
	 * @return
	 */
	private static boolean isAlreadyFetched(From<?, ?> from, String attribute) {

		for (Fetch<?, ?> f : from.getFetches()) {

			boolean sameName = f.getAttribute().getName().equals(attribute);

			if (sameName && f.getJoinType().equals(JoinType.LEFT)) {
				return true;
			}
		}

		return false;
	}
}

Output:
【漏洞类型】盲SQL注入漏洞
【严重性】High
【漏洞摘要】此代码存在一个潜在的盲SQL注入漏洞，特别是在使用`Sort`与`@Query`注解结合时。当用户输入的排序属性包含函数调用时，这些函数调用会被直接附加到SQL查询中，而没有进行验证或转义。例如，在`findByLastname`方法中，用户可以传入类似"LENGTH(firstname)"的排序属性，这可能会导致意外的SQL行为或安全问题。
【关键代码模式】
1. `applySorting`函数中的排序属性处理，特别是`getOrderClause`函数。
2. 使用`@Query`注解的查询方法，结合`Sort`参数。
3. `JpaSort`类中的排序属性方法。
【修复方法说明】修复方法通过添加`checkSortExpression`函数来验证排序属性是否包含函数调用，并在包含时抛出异常，以防止潜在的SQL注入攻击。同时，引入了`JpaSort.unsafe`方法，允许用户在必要时使用包含函数的排序属性。


Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
doc/lxc-attach.sgml.in
### 代码内容：
<!--

lxc: linux Container library

(C) Copyright IBM Corp. 2007, 2008

Authors:
Daniel Lezcano <daniel.lezcano at free.fr>

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

-->

<!DOCTYPE refentry PUBLIC @docdtd@ [

<!ENTITY commonoptions SYSTEM "@builddir@/common_options.sgml">
<!ENTITY seealso SYSTEM "@builddir@/see_also.sgml">
]>

<refentry>

  <docinfo><date>@LXC_GENERATE_DATE@</date></docinfo>

  <refmeta>
    <refentrytitle>lxc-attach</refentrytitle>
    <manvolnum>1</manvolnum>
  </refmeta>

  <refnamediv>
    <refname>lxc-attach</refname>

    <refpurpose>
      start a process inside a running container.
    </refpurpose>
  </refnamediv>

  <refsynopsisdiv>
    <cmdsynopsis>
      <command>lxc-attach</command>
      <arg choice="req">-n <replaceable>name</replaceable></arg>
      <arg choice="opt">-a <replaceable>arch</replaceable></arg>
      <arg choice="opt">-e</arg>
      <arg choice="opt">-s <replaceable>namespaces</replaceable></arg>
      <arg choice="opt">-R</arg>
      <arg choice="opt">--keep-env</arg>
      <arg choice="opt">--clear-env</arg>
      <arg choice="opt">-- <replaceable>command</replaceable></arg>
    </cmdsynopsis>
  </refsynopsisdiv>

  <refsect1>
    <title>Description</title>

    <para>
      <command>lxc-attach</command> runs the specified
      <replaceable>command</replaceable> inside the container
      specified by <replaceable>name</replaceable>. The container
      has to be running already.
    </para>
    <para>
      If no <replaceable>command</replaceable> is specified, the
      current default shell of the user running
      <command>lxc-attach</command> will be looked up inside the
      container and executed. This will fail if no such user exists
      inside the container or the container does not have a working
      nsswitch mechanism.
    </para>

  </refsect1>

  <refsect1>

    <title>Options</title>

    <variablelist>

      <varlistentry>
	<term>
	  <option>-a, --arch <replaceable>arch</replaceable></option>
	</term>
	<listitem>
	  <para>
	    Specify the architecture which the kernel should appear to be
	    running as to the command executed. This option will accept the
	    same settings as the <option>lxc.arch</option> option in
	    container configuration files, see
	    <citerefentry>
	      <refentrytitle><filename>lxc.conf</filename></refentrytitle>
	      <manvolnum>5</manvolnum>
	    </citerefentry>. By default, the current archictecture of the
	    running container will be used.
	  </para>
	</listitem>
      </varlistentry>

      <varlistentry>
	<term>
	  <option>
      -e, --elevated-privileges <replaceable>privileges</replaceable>
    </option>
	</term>
	<listitem>
	  <para>
	    Do not drop privileges when running
	    <replaceable>command</replaceable> inside the container. If
	    this option is specified, the new process will
	    <emphasis>not</emphasis> be added to the container's cgroup(s)
	    and it will not drop its capabilities before executing.
	  </para>
    <para>
      You may specify privileges, in case you do not want to elevate all of
      them, as a pipe-separated list, e.g.
      <replaceable>CGROUP|LSM</replaceable>. Allowed values are
      <replaceable>CGROUP</replaceable>, <replaceable>CAP</replaceable> and
      <replaceable>LSM</replaceable> representing cgroup, capabilities and
      restriction privileges respectively.
    </para>
	  <para>
	    <emphasis>Warning:</emphasis> This may leak privileges into the
	    container if the command starts subprocesses that remain active
	    after the main process that was attached is terminated. The
	    (re-)starting of daemons inside the container is problematic,
	    especially if the daemon starts a lot of subprocesses such as
	    <command>cron</command> or <command>sshd</command>.
	    <emphasis>Use with great care.</emphasis>
	  </para>
	</listitem>
      </varlistentry>

      <varlistentry>
	<term>
	  <option>-s, --namespaces <replaceable>namespaces</replaceable></option>
	</term>
	<listitem>
	  <para>
	    Specify the namespaces to attach to, as a pipe-separated list,
	    e.g. <replaceable>NETWORK|IPC</replaceable>. Allowed values are
	    <replaceable>MOUNT</replaceable>, <replaceable>PID</replaceable>,
	    <replaceable>UTSNAME</replaceable>, <replaceable>IPC</replaceable>,
	    <replaceable>USER </replaceable> and
	    <replaceable>NETWORK</replaceable>. This allows one to change
	    the context of the process to e.g. the network namespace of the
	    container while retaining the other namespaces as those of the
	    host.
	  </para>
	  <para>
	    <emphasis>Important:</emphasis> This option implies
	    <option>-e</option>.
	  </para>
	</listitem>
      </varlistentry>

      <varlistentry>
	<term>
	  <option>-R, --remount-sys-proc</option>
	</term>
	<listitem>
	  <para>
	    When using <option>-s</option> and the mount namespace is not
	    included, this flag will cause <command>lxc-attach</command>
	    to remount <replaceable>/proc</replaceable> and
	    <replaceable>/sys</replaceable> to reflect the current other
	    namespace contexts.
	  </para>
	  <para>
	    Please see the <emphasis>Notes</emphasis> section for more
	    details.
	  </para>
	  <para>
	    This option will be ignored if one tries to attach to the
	    mount namespace anyway.
	  </para>
	</listitem>
      </varlistentry>

      <varlistentry>
	<term>
	  <option>--keep-env</option>
	</term>
	<listitem>
	  <para>
	    Keep the current environment for attached programs. This is
	    the current default behaviour (as of version 0.9), but is
	    is likely to change in the future, since this may leak
	    undesirable information into the container. If you rely on
	    the environment being available for the attached program,
	    please use this option to be future-proof. In addition to
	    current environment variables, container=lxc will be set.
	  </para>
	</listitem>
      </varlistentry>

      <varlistentry>
	<term>
	  <option>--clear-env</option>
	</term>
	<listitem>
	  <para>
	    Clear the environment before attaching, so no undesired
	    environment variables leak into the container. The variable
	    container=lxc will be the only environment with which the
	    attached program starts.
	  </para>
	</listitem>
      </varlistentry>

     </variablelist>

  </refsect1>

  &commonoptions;

  <refsect1>
    <title>Examples</title>
      <para>
        To spawn a new shell running inside an existing container, use
        <programlisting>
          lxc-attach -n container
        </programlisting>
      </para>
      <para>
        To restart the cron service of a running Debian container, use
        <programlisting>
          lxc-attach -n container -- /etc/init.d/cron restart
        </programlisting>
      </para>
      <para>
        To deactivate the network link eth1 of a running container that
        does not have the NET_ADMIN capability, use either the
        <option>-e</option> option to use increased capabilities,
        assuming the <command>ip</command> tool is installed:
        <programlisting>
          lxc-attach -n container -e -- /sbin/ip link delete eth1
        </programlisting>
        Or, alternatively, use the <option>-s</option> to use the
        tools installed on the host outside the container:
        <programlisting>
          lxc-attach -n container -s NETWORK -- /sbin/ip link delete eth1
        </programlisting>
      </para>
  </refsect1>

  <refsect1>
    <title>Compatibility</title>
    <para>
      Attaching completely (including the pid and mount namespaces) to a
      container requires a kernel of version 3.8 or higher, or a
      patched kernel, please see the lxc website for
      details. <command>lxc-attach</command> will fail in that case if
      used with an unpatched kernel of version 3.7 and prior.
    </para>
    <para>
      Nevertheless, it will succeed on an unpatched kernel of version 3.0
      or higher if the <option>-s</option> option is used to restrict the
      namespaces that the process is to be attached to to one or more of
      <replaceable>NETWORK</replaceable>, <replaceable>IPC</replaceable>
      and <replaceable>UTSNAME</replaceable>.
    </para>
    <para>
      Attaching to user namespaces is supported by kernel 3.8 or higher
      with enabling user namespace.
    </para>
  </refsect1>

  <refsect1>
    <title>Notes</title>
    <para>
      The Linux <replaceable>/proc</replaceable> and
      <replaceable>/sys</replaceable> filesystems contain information
      about some quantities that are affected by namespaces, such as
      the directories named after process ids in
      <replaceable>/proc</replaceable> or the network interface information
      in <replaceable>/sys/class/net</replaceable>. The namespace of the
      process mounting the pseudo-filesystems determines what information
      is shown, <emphasis>not</emphasis> the namespace of the process
      accessing <replaceable>/proc</replaceable> or
      <replaceable>/sys</replaceable>.
    </para>
    <para>
      If one uses the <option>-s</option> option to only attach to
      the pid namespace of a container, but not its mount namespace
      (which will contain the <replaceable>/proc</replaceable> of the
      container and not the host), the contents of <option>/proc</option>
      will reflect that of the host and not the container. Analogously,
      the same issue occurs when reading the contents of
      <replaceable>/sys/class/net</replaceable> and attaching to just
      the network namespace.
    </para>
    <para>
      To work around this problem, the <option>-R</option> flag provides
      the option to remount <replaceable>/proc</replaceable> and
      <replaceable>/sys</replaceable> in order for them to reflect the
      network/pid namespace context of the attached process. In order
      not to interfere with the host's actual filesystem, the mount
      namespace will be unshared (like <command>lxc-unshare</command>
      does) before this is done, esentially giving the process a new
      mount namespace, which is identical to the hosts's mount namespace
      except for the <replaceable>/proc</replaceable> and
      <replaceable>/sys</replaceable> filesystems.
    </para>
  </refsect1>

  <refsect1>
    <title>Security</title>
    <para>
      The <option>-e</option> and <option>-s</option> options should
      be used with care, as it may break the isolation of the containers
      if used improperly.
    </para>
  </refsect1>

  &seealso;

  <refsect1>
    <title>Author</title>
    <para>Daniel Lezcano <email>daniel.lezcano@free.fr</email></para>
  </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:2
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:nil
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
-->

Output:
【漏洞类型】权限提升漏洞
【严重性】High
【漏洞摘要】原始代码中，`lxc-attach`命令的`-e`和`-s`选项允许用户在容器中以提升的权限运行命令，并且没有充分的隔离机制来防止潜在的输入伪造攻击（通过TIOCSTI ioctl调用）。此外，旧版本的命令在用户未被放置在关键子系统的可写cgroup中时，可能会导致意外的行为，而新版本的命令则进行了相应的检查，但这也可能对某些用户造成影响。
【关键代码模式】`-e`，`-s`，`TIOCSTI`，`ioctl`，`cgroup`，`namespaces`。
【修复方法说明】修复方法通过尝试在容器中或主机上分配伪终端（pty）来解决输入伪造攻击的问题，并且确保用户在关键子系统的可写cgroup中运行，以提高安全性。最佳实践包括在执行高权限操作时使用伪终端，并确保用户在适当的cgroup中运行以限制其权限。